您的位置:首页 > 编程语言 > Java开发

【Java基础】IO总结

2016-03-13 15:46 561 查看
概述

一:输入/输出流

 
一个流就是程序与外界通信的一条通道,它可以用来连续的传送数据项。
Input/Output(I / O)流表示输入源或输出目的地。一个流可以代表许多不同种类的来源和目的地,包括磁盘文件,设备,其他的程序,存储器阵列(memory
arrays)。
 
流支持许多不同类型的数据,包括简单的字节、原始数据类型、本地化字符和对象。有些流只是简单的传      送数据,还有些流以适当的方式操纵并转换数据。

 
不管它们内部是怎么工作的,所有的流对使用它们的程序来说呈现出同样的、简单的模型,那就是:流是一个序列的数据。
 
二:流的分类

 
可以从不同的角度对流进行分类:
        1.处理的数据单位不同,可分为:字符流,字节流
        2.数据流方向不同,可分为:输入流,输出流
        3.功能不同,可分为:节点流,处理流

 
字节流(Byte Streams:
 字节流是执行基于8位字节的输入和输出,它一次读写一字节的数据。字节流是I
/ O的最底层流技术,因此,如果你正在阅读或写入字符数据的最佳方法是使用字符流。其他流类型是建立在字节流之上的(如Java中的InputStream、OutputStream)。

 
字符流(Chcaracter Streams:
   字符流是执行基于16位字节(即两字节)的输入和输出,它一次读写一个字符(两个字节)的数据。所有的字符流类都是从Reader、Writer两个类延伸下来的,我们可以使用FileReader、FileWriter类进行读写I/O文件

 
1. 和 2.都比较好理解,对于根据功能分类的,可以这么理解:
节点流:节点流从一个特定的数据源读写数据。即节点流是直接操作文件,网络等的流,例如FileInputStream和FileOutputStream,他们直接从文件中读取或往文件中写入字节流。


     
       
 处理流
“连接”在已存在的流(节点流或处理流)之上通过对数据的处理为程序提供更为强大的读写功能。过滤流是使用一个已经存在的输入流或输出流连接创建的,过滤流就是对节点流进行一系列的包装。例如BufferedInputStream和BufferedOutputStream,使用已经存在的节点流来构造,提供带缓冲的读写,提高了读写的效率,以及DataInputStream和DataOutputStream,使用已经存在的节点流来构造,提供了读写Java中的基本数据类型的功能。他们都属于过滤流。





字节流(byte stream)

   字节流是执行基于8位字节的输入和输出,它一次读写一字节的数据。字节流是I / O的最底层流技术,因此,如果你正在阅读或写入字符数据的最佳方法是使用字符流。其他流类型是建立在字节流之上的(如Java中的InputStream、OutputStream)。
API类关系
java.lang.Object
           java.io.InputStream
java.lang.Object
          java.io.OutputStream
字节流类谱图:





 
 
通过上面两张关于流的类关系图,可以看到流的应用类都是由InputStream、OutputStream两类延伸(扩展)开来的。继承自InputStream/OutputStream的流都是用于向程序中输入/输出数据,且数据的单位都是字节(byte=8bit),

如上图中,深色的为节点流,浅色的为处理流。

IO 包中的常见对象

1)字节流:
字节输入流
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.
字节输出流
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
指定输出是否追加
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output stream.
BufferedOutputStream(OutputStream out, int size)
Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

2)字符流:
字符输入流
FileReader(Filefile)
Creates a new FileReader, given theFile to read from.
FileReader(StringfileName)
Creates a new FileReader, given thename of the file to read from.
BufferedReader(Readerin)
Creates a buffering character-inputstream that uses a default-sized input buffer.
BufferedReader(Readerin, int sz)
Creates a buffering character-inputstream that uses an input buffer of the specified size.
字符输出流
BufferedReader(Readerin)
Creates a buffering character-inputstream that uses a default-sized input buffer.
BufferedReader(Readerin, int sz)
Creates a buffering character-inputstream that uses an input buffer of the specified size.
BufferedWriter(Writerout)
Creates a buffered character-outputstream that uses a default-sized output buffer.
BufferedWriter(Writerout, int sz)
Creates a new bufferedcharacter-output stream that uses an output buffer of the given size.

3)转换流:
InputStreamReader(InputStreamin)
Creates an InputStreamReader thatuses the default charset.
InputStreamReader(InputStreamin, String charsetName)
Creates an InputStreamReader thatuses the named charset.OutputStreamWriter(OutputStreamout)
Creates an OutputStreamWriter thatuses the default character encoding.
OutputStreamWriter(OutputStreamout, String charsetName)
Creates an OutputStreamWriter thatuses the named charset.

4)文件对象:
File(File parent,String child)
Creates a new File instance from aparent abstract pathname and a child pathname string.
File(Stringpathname)
Creates a new File instance byconverting the given pathname string into an abstract pathname.
File(Stringparent, String child)
Creates a new File instance from aparent pathname string and a child pathname string.

5)打印流:
PrintWriter(Filefile)
Creates a new PrintWriter, withoutautomatic line flushing, with the specified file.
PrintWriter(OutputStreamout)
Creates a new PrintWriter, withoutautomatic line flushing, from an existing OutputStream.
PrintStream(OutputStreamout)
Creates a new print stream.
PrintStream(Filefile)
Creates a new print stream, withoutautomatic line flushing, with the specified file.

 
使用
一、字节流
1)使用InputStream读取文件得到字节数组,并利用newString(b,0,len,"UTF-8")将字节数组转换为字符串输出

 

        InputStream input = new FileInputStream(file);
StringBuffer buffer = newStringBuffer();
byte[] bytes = new byte[1024];
int len = 0;
while((len=input.read(bytes))!=-1){
String str = newString(bytes,0,len,"UTF-8");
buffer.append(str);
System.out.println(buffer.toString());
}
input.close();

 
2)
因为BufferedInputStream、BufferedOutputStream是处理流,FileInputStream、FileOutputStream是节点流,
所以使用BufferedInputStream、BufferedOutputStream分别FileInputStream、FileOutputStream进行封装

    

InputStream in = new FileInputStream(file);
BufferedInputStreambis = new BufferedInputStream(in);
byte[]buffer = new byte[1024];
intb ;
//从文件中按字节读取内容,到文件尾部时read方法将返回-1
while((b=bis.read(buffer))!=-1){
//将读取的字节转为字符串对象
Stringchunk = new String(buffer,0,b);
System.out.println(chunk);
}
String str = "dsklasdfj";
BufferedOutputStreamout = new BufferedOutputStream(new FileOutputStream(file));
out.write(str.getBytes());
out.close();


 
ps:
FileOutputStream有个构造方法,可指定输出是否追加。
FileOutputStream(File file,boolean append)
 
 

二、字符流
1)使用BufferedReader按字符流读取文件,文件编码与读取编码不一致时会出现乱码

 

BufferedReaderin = new BufferedReader(new FileReader(file));
Stringline = null;
while((line=in.readLine())!=null){
System.out.println(line);
}
in.close();

 
2)转换流InputStreamReader、OutputStreamWriter可以对字节和字符进行转换,指定使用“UTF-8”编码方式读取文件

 

 BufferedReaderin = new BufferedReader(new InputStreamReader(newFileInputStream(file),"UTF-8"));
Stringline = null;
while((line=in.readLine())!=null){
System.out.println(line);
}
in.close();

 

三、转换流

InputStreamReader:字节到字符的桥梁(将读取的字节流转换为字符流);

OutputStreamWriter:字符到字节的桥梁(将输入的字符流抓换为字节流);

构造函数
InputStreamReader(InputStreamin)
使用默认的编码表GBK创建一个InputStreamReader
InputStreamReader(InputStreamin, String charsetName)
指定编码表创建一个InputStreamReader
OutputStreamWriter(OutputStreamout)
使用默认的编码表GBK创建一个OutputStreamWriter
OutputStreamWriter(OutputStreamout, String charsetName)
指定编码表创建一个OutputStreamWriter

 

 

 

public class OutputStreamWriterTest {

publicstatic void main(String[] args) throws IOException {
Filefile = new File("e:"+File.separator+
"javaworkspace"+File.separator+"iotestfile"+File.separator+"test.txt");
OutputStreamWriterout = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
out.write("我我我");
out.close();
InputStreamReaderin = new InputStreamReader(new FileInputStream(file),"UTF-8");
StringBufferbuffer = new StringBuffer();
char[] cbuf = new char[1024]; //字符流,所以要用char数组来缓存
intlen = 0;
while((len=in.read(cbuf))!=-1){
buffer.append(cbuf,0,len);
}
System.out.println(buffer);
in.close();
}

}

 

 
总结:所有字节流都是以InputStream、OutputStream为基础的,它是一个抽象类,所以不可实例化,更没有传入文件实例的构造函数,一般当做父类引用。
OutputStream out =new FileOutputStream(file,true);
当需要读取文件时就使用FileInputStream、FileOutputStream,它们是InputStream、OutputStream的子类,又是节点流,所以可以使用BufferedInputStream、BufferedOutputStream、DataInputStream、DataOutputStream等处理流对它进行包装。
在需要用到字符流的时候,一般不直接使用字符流,要使用转换流来进行包装,因为有编码的问题,需要指定。使用转换流可以指定编码。
InputStreamReader(InputStreamin, String charsetName)
OutputStreamWriter(OutputStreamout, String charsetName)
 
当使用字节流进行读操作时,遇到中文编码问题,可以在用String对byte数组进行转换时指定编码
String str = newString(bytes,0,len,"UTF-8");
使用字节流进行写操作时,遇到中文编码问题,可以使用字节字符转换流对字符转成字节,
OutputStreamWriterout = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");

参考:

http://andieguo.com/2014/11/05/java-io/
http://15838341661-139-com.iteye.com/blog/2003711
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: