JAVA IO

一 JAVA IO的操作写一次忘一次,这里做个总结

二 在使用上只需要记住4点

1 一张架构图:

JAVA IO

 2 JAVA IO使用的是包装器模式(比如说:用InputStreamReader初始化FileReader)

3 用缓冲流节省性能,不要直接使用原始的输入输出流。

4 用完之后关掉流,在finally块中关闭流,不要在try或者catch块中关闭。关闭外层的流(包装流)会把内层的流关闭,java输入输出流都要关闭。

三 一般的操作就是:

1 从XXX中得到最开始的流,比如InputStream

2 用缓冲流给最开始的流包一层

举例:

File file = new File();

InputStream in = new InputStream(file,"utf-8");

BufferedInputStream bin = new BufferedInputStream(in);

四 write和read方法

1 write和read的操作对象是byte字节

2 read有3个方法,一般使用的是read(byte[] b),读取一定量的字节到直接数组b中,返回值就是读取的直接的长度。

3 读取到了直接数组中就要写字节了,用的一般是write(b,start,end),把字符数组b的第start到end个字节写到输出流中。

4 一般的写法如下:

File inFile = new File("xxx");

BufferedInputStream bin = new BufferedInputStream(new FileInputStream(inFile,"utf-8"));

File outFile = new File("xxx");

BufferedOutputStream bout = new BufferedOutputStream(new FileOutstream(outFile,"utf-8"));

byte[] b = new byte[1024];

int len = 0;

while(len = bin.read(b) != -1){

         bout.write(b,0,len);

}

bout.flush;

bout.close();

bin.close();//这里应该写在finally块中的,在编辑器中会有提示的,我这里直接在文本中敲的,所以就不写了