要点
流的write和read都是一个字节或一个字符操作的,太慢。所以缓冲区就出现了,虽然还是一个个操作,但是把需要操作的数据打包到缓冲区,一坨一坨的从硬盘到OS到jvm到程序(或流程反过来),就快很多。
用缓冲流进行文件复制
经测试,复制5.18Mb的文件不用缓冲区需要13351毫秒,用缓冲区需要112毫秒。
import java.io.*;
public class FileCopyT {
public static void main(String[] args) throws IOException {
//long e = System.currentTimeMillis();
File file = new File("C:\\Users\\25852\\Pictures\\Camera Roll\\wallhaven-md762m_3840x2160.png");
int size = (int)file.length();//获取文件大小
FileInputStream fileIn = new FileInputStream(file);//创建输入流对象
BufferedInputStream BufffileIn =new BufferedInputStream(fileIn,size);//创建输入流缓冲流对象
FileOutputStream fileOut = new FileOutputStream("D:\\JavaSE\\基础语法\\src\\com\\javaSE\\CommonAPI\\e.png");//创建输出流对象
BufferedOutputStream BufffileOut = new BufferedOutputStream(fileOut,size);//创建输出流缓冲流
byte[] bytes = new byte[size];
int i = 0;
int re = 0;
while ((re=BufffileIn.read())!=-1){
bytes[i++]=(byte)re;
}
BufffileOut.write(bytes);
//long d = System.currentTimeMillis();//13351
//System.out.println(d-e);
}
}
复制代码