通过不使用缓冲流代码与使用缓冲流代码来对比测试一波:
1package person.xsc.praticeIII; 2import java.io.BufferedInputStream; 3import java.io.BufferedOutputStream; 4import java.io.File; 5import java.io.FileInputStream; 6import java.io.FileNotFoundException; 7import java.io.FileOutputStream; 8import java.io.IOException; 9public class Copy3 { 10 public static void main(String[] args) throws FileNotFoundException{ 11 // TODO Auto-generated method stub 12 String srcPath="C:\\Users\\你是小朱老师呀\\Desktop\\JAVA编程.DOC"; 13 String destPath="C:\\Users\\你是小朱老师呀\\Desktop\\XSC\\test4.DOCX"; 14 //1.造源文件与目标文件 15 File srcFile = new File(srcPath); 16 File destFile = new File(destPath); 17 //2.造节点流 18 FileInputStream fis = new FileInputStream((srcFile)); 19 FileOutputStream fos = new FileOutputStream(destFile); 20 //文件大小 21 long dataSize=srcFile.length(); 22 System.out.println("文件大小:" + dataSize + " B"); 23 //不使用缓冲流去复制 24 long start0 = System.currentTimeMillis(); 25 byte[] byte0 = new byte[1024]; 26 int temp0 = 0 ; 27 try{ 28 while((temp0=fis.read(byte0))!=-1){ // 开始拷贝 29 fos.write(byte0,0,temp0) ; // 边读边写 30 } 31 System.out.println("不使用缓冲流拷贝完成!") ; 32 }catch(IOException e){ 33 e.printStackTrace() ; 34 System.out.println("不使用缓冲流拷贝失败!") ; 35 } 36 try{ 37 fis.close() ; // 关闭 38 fos.close() ; // 关闭 39 }catch(IOException e){ 40 e.printStackTrace() ; 41 } 42 long end0 = System.currentTimeMillis(); 43 //FileUtils.sizeOf(localFileCache) 44 System.out.println("不使用缓冲流复制需要 " + (end0-start0) + " ms"+"复制速度为:" + dataSize / (end0-start0) + " B/ms"); 45 //使用缓冲流去复制 46 BufferedInputStream bis = new BufferedInputStream(new FileInputStream((srcFile))); 47 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); 48 long start1 = System.currentTimeMillis(); 49 byte [] byte1 = new byte[1024]; 50 int temp1 = 0 ; 51 try{ 52 while((temp1=bis.read(byte1))!=-1){ 53 bos.write(byte1,0,temp1) ; 54 } 55 System.out.println("使用缓冲流拷贝完成!") ; 56 }catch(IOException e){ 57 e.printStackTrace() ; 58 System.out.println("使用缓冲流拷贝失败!") ; 59 } 60 try{ 61 fis.close() ; // 关闭 62 fos.close() ; // 关闭 63 }catch(IOException e){ 64 e.printStackTrace() ; 65 } 66 long end1 = System.currentTimeMillis(); 67 System.out.println("使用缓冲流复制需要 " + (end1-start1) + " ms"+"复制速度为:" + dataSize / (end1-start1) + " B/ms"); 68 } 69 70} 71输出: 72文件大小:405504 B 73不使用缓冲流拷贝完成! 74不使用缓冲流复制需要 8 ms复制速度为:50688 B/ms 75使用缓冲流拷贝完成! 76使用缓冲流复制需要 2 ms复制速度为:202752 B/ms
通过上面程序运行结果发现:加入缓冲处理流的复制速度将有明显的提升。至于为什么复制速度会提升,是因为不带缓冲的复制操作,每读一个字节就要写入一个字节,由于涉及磁盘的IO操作相比内存的操作要慢很多,所以不带缓冲的流效率很低。带缓冲的流,可以一次读很多字节,但不向磁盘中写入,只是先放到内存里。等凑够了缓冲区大小的时候一次性写入磁盘,这种方式可以减少磁盘操作次数,速度就会提高很多!
