最近公司的项目用到文件拷贝,由于涉及到的大量大文件的拷贝工作,代码性能问题显得尤为重要,所以写了以下例子对几种文件拷贝操作做一比较:
0、文件拷贝测试方法
1 public static void fileCopy(String source, String target,int type) { 2 Date start = new Date(); 3 File in = null; 4 File out = null; 5 FileInputStream fis = null; 6 FileOutputStream fos = null; 7 try { 8 in = new File(source); 9 out = new File(target); 10 switch (type) { 11 case 1: 12 copyer1(in, out, fis, fos); 13 break; 14 case 2: 15 copyer2(in, out, fis, fos); 16 break; 17 case 3: 18 copyer3(in, out, fis, fos); 19 break; 20 case 4: 21 copyer4(in, out, fis, fos); 22 break; 23 default: 24 break; 25 } 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } finally { 29 if (fis != null) { 30 try { 31 fis.close(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 } 36 if (fos != null) { 37 try { 38 fos.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 Date end = new Date(); 44 System.out.println("方法"+type+"用时:"+(end.getTime() - start.getTime())+" ms!"); 45 } 46 }
方式一:一次读取全部数据
1 /** 2 * 一次全部读取文件内容 3 */ 4 @SuppressWarnings("resource") 5 public static void copyer1(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ 6 fis = new FileInputStream(in); 7 int size = fis.available(); 8 byte[] buffer = new byte[size]; 9 fis.read(buffer); 10 fos = new FileOutputStream(out); 11 fos.write(buffer); 12 fos.flush(); 13 }
方式二:每次读入固定字节的数据
1 /** 2 * 每次读取固定字节的数据 3 */ 4 @SuppressWarnings("resource") 5 public static void copyer2(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ 6 7 fis = new FileInputStream(in); 8 fos = new FileOutputStream(out); 9 byte[] buffer = new byte[1024]; 10 while (fis.read(buffer) != -1) { 11 fos.write(buffer); 12 } 13 fos.flush(); 14 }
方式三:每次读取一行数据,适合按行解析数据的场景
1 /** 2 * 每次读取一行数据 3 */ 4 @SuppressWarnings("resource") 5 public static void copyer3(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ 6 7 fis = new FileInputStream(in); 8 fos = new FileOutputStream(out); 9 BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 10 String line = null; 11 while ((line = br.readLine()) != null) { 12 fos.write(line.getBytes()); 13 } 14 fos.flush(); 15 }
方式四:每次读取一个字符,~_~,想想都累
1 /** 2 * 每次读取一个字节 3 */ 4 @SuppressWarnings("resource") 5 public static void copyer4(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ 6 7 fis = new FileInputStream(in); 8 fos = new FileOutputStream(out); 9 int i = 0; 10 while ((i = fis.read()) != -1) { 11 fos.write(i); 12 } 13 fos.flush(); 14 } 15 }
最后:测试用main函数
1 public static void main(String[] args) { 2 String source = "e:\\in.txt"; 3 String target = "e:\\out.txt"; 4 for (int i = 1; i < 5; i++) { 5 fileCopy(source, target, i); 6 } 7 }
测试文件:
运行结果:
时间: 2024-11-08 20:39:22