Java语言中一般的输入与输出流类,都是采用单字节的读取方法,进行数据I/O操作的。也就是每次只读取或写入一个字节的数据,这种方法显然繁琐而低效。其读取与写入的流程图,如图1所示:
打个比方:
假设在A地有100本图书,需要把这些图书从A地运送到B地。
如果每次从A地只拿一本图书到B地,则需要往返A、B两地100次;
如果每次从A地取10本图书到B地,则只需要10次就可以完成这个任务。
显然,后者的效率要高。这个故事中的“每次拿10本”相当于I/O操作的“缓冲区”。
开设一个数据缓冲区来每次读取一个数据块,提高系统性能,这在网络数据传输中显得尤其重要。采用数据缓冲类读取与写入的流程图,如图2所示:
案例如下:
package cn.optimize.len;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ReadWriteWithBuffer {
public static void main(String[] args) {
ReadWriteWithBuffer rw = new ReadWriteWithBuffer();
try{
long startTime = System.currentTimeMillis();
rw.readWrite("D:/temp/uwp.txt","D:/temp/uwp2.txt");
long endTime = System.currentTimeMillis();
System.out.println("直接读取与写入耗时:"+(endTime-startTime)+"ms");
startTime = System.currentTimeMillis();
rw.readWriteBuffer("D:/temp/uwp.txt","D:/temp/uwp3.txt");
endTime = System.currentTimeMillis();
System.out.println("通过系统缓冲区读取与写入时:"+(endTime-startTime)+"ms");
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 直接通过文件输入/输出来读取与写入
* @param fileFrom 源文件
* @param fileTo 目的文件
* @throws IOException
*/
public static void readWrite(String fileFrom,String fileTo)throws IOException{
InputStream in = null;
OutputStream out = null;
try{
in = new FileInputStream(fileFrom);
out = new FileOutputStream(fileTo);
while(true){
int bytedata = in.read();
if(bytedata==-1)
break;
out.write(bytedata);
}
}finally{
if(in != null)
in.close();
if(out != null)
out.close();
}
}
/**
*通过系统缓冲区来读取与写入
* @param fileFrom 源文件
* @param fileTo 目的文件
* @throws IOException
*/
public static void readWriteBuffer(String fileFrom,String fileTo)throws IOException{
InputStream inBuffer = null;
OutputStream outBuffer = null;
try{
InputStream in = new FileInputStream(fileFrom);
inBuffer = new BufferedInputStream(in);
OutputStream out = new FileOutputStream(fileTo);
outBuffer = new BufferedOutputStream(out);
while(true){
int bytedata = inBuffer.read();
if(bytedata==-1)
break;
out.write(bytedata);
}
}finally{
if(inBuffer != null)
inBuffer.close();
if(outBuffer != null)
outBuffer.close();
}
}
}
在上面的例子中,读取D:/temp/uwp.txt文件,该文件是一个221KB的文本文件,然后将读取的内容写入到另一文件中,并采用两种不同的方式:
1)直接读取与写入
2)采用系统输入输出缓冲类读取与写入
编译上述文件,其输出的信息如下:
可知,如果文件较大时,建议采用系统缓冲类,来进行文件的读取与写入操作。