1. 需求:把f:\Jick.mp4 复制到当前项目目录下的copy.mp4中
字节流四种方式复制文件:
• 基本字节流一次读写一个字节
• 基本字节流一次读写一个字节数组
• 高效字节流一次读写一个字节
• 高效字节流一次读写一个字节数组
2. 代码示例:
1 package com.himi.iocopy; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 /* 10 * 需求:把f:\Jick.mp4复制到当前项目目录下的copy.mp4中 11 * 12 * 字节流四种方式复制文件: 13 * 基本字节流一次读写一个字节(method1): 共耗时:138872 毫秒 14 * 基本字节流一次读写一个字节数组(method2): 共耗时:160 毫秒 15 * 高效字节流一次读写一个字节(method3): 共耗时:643 毫秒 16 * 高效字节流一次读写一个字节数组(method4): 共耗时:40 毫秒 17 */ 18 public class IOCopy { 19 public static void main(String[] args) throws IOException { 20 long start = System.currentTimeMillis(); 21 22 23 //method1("f:\Jick.mp4", "copy1.mp4"); 24 //method2("f:\Jick.mp4", "copy2.mp4"); 25 //method3("f:\Jick.mp4", "copy3.mp4"); 26 method4("f:\Jick.mp4", "copy4.mp4"); 27 long end = System.currentTimeMillis(); 28 System.out.println("共耗时:" + (end - start) + "毫秒"); 29 30 31 32 } 33 34 // 高效字节流一次读写一个字节数组: 35 public static void method4(String srcString, String destString) 36 throws IOException { 37 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( 38 srcString)); 39 BufferedOutputStream bos = new BufferedOutputStream( 40 new FileOutputStream(destString)); 41 42 byte[] bys = new byte[1024]; 43 int len = 0; 44 while ((len = bis.read(bys)) != -1) { 45 bos.write(bys, 0, len); 46 } 47 48 bos.close(); 49 bis.close(); 50 } 51 52 // 高效字节流一次读写一个字节: 53 public static void method3(String srcString, String destString) 54 throws IOException { 55 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( 56 srcString)); 57 BufferedOutputStream bos = new BufferedOutputStream( 58 new FileOutputStream(destString)); 59 60 int by = 0; 61 while ((by = bis.read()) != -1) { 62 bos.write(by); 63 64 } 65 66 bos.close(); 67 bis.close(); 68 } 69 70 // 基本字节流一次读写一个字节数组 71 public static void method2(String srcString, String destString) 72 throws IOException { 73 FileInputStream fis = new FileInputStream(srcString); 74 FileOutputStream fos = new FileOutputStream(destString); 75 76 byte[] bys = new byte[1024]; 77 int len = 0; 78 while ((len = fis.read(bys)) != -1) { 79 fos.write(bys, 0, len); 80 } 81 82 fos.close(); 83 fis.close(); 84 } 85 86 // 基本字节流一次读写一个字节 87 public static void method1(String srcString, String destString) 88 throws IOException { 89 FileInputStream fis = new FileInputStream(srcString); 90 FileOutputStream fos = new FileOutputStream(destString); 91 92 int by = 0; 93 while ((by = fis.read()) != -1) { 94 fos.write(by); 95 } 96 97 fos.close(); 98 fis.close(); 99 } 100 101 }