Java输入输出流复制文件所用时间对比

时间:2022-04-13 22:05:57

废话不多说,关键代码如下所述:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.edu.xynu;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOUnitCopy {
//按字节
public static void copyByByte(File srcFile,File destFile) throws IOException{
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile);
int i;
while((i=fis.read())!=-1){
fos.write(i);
}
fis.close();
fos.close();
}
//按字节数组
public static void copyByByteArray(File srcFile,File destFile) throws IOException{
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile);
byte []buf=new byte[10*1024];
int i;
while((i=fis.read(buf, 0, buf.length))!=-1){
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
//字节缓冲流
public static void copyByBuff(File srcFile,File destFile) throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));
int i;
while((i=bis.read())!=-1){
bos.write(i);
}
bos.flush();
bis.close();
bos.close();
}
//字节数组批量读取 缓冲输出流写入
public static void copyByBuffArray(File srcFile,File destFile) throws IOException{
FileInputStream bis=new FileInputStream(srcFile);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));
byte [] buf=new byte[10*1024];
int len;
while((len=bis.read(buf,0,buf.length))!=-1){
bos.write(buf,0,len);
}
bos.flush();
bis.close();
bos.close();
}
}
package com.edu.xynu;
import java.io.File;
import java.io.IOException;
public class IOUnitsCopyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
long start=System.currentTimeMillis();
// IOUnitCopy.copyByByte(new File("c:\\1.mp3"), new File(
// "c:\\2.mp3"));//90713ms
// IOUnitCopy.copyByByteArray(new File("c:\\1.mp3"), new File(
// "c:\\3.mp3"));//41ms
// IOUnitCopy.copyByBuff(new File("c:\\1.mp3"), new File(
// "c:\\4.mp3"));//556ms
// IOUnitCopy.copyByByteArray(new File("c:\\1.mp3"), new File(
// "c:\\5.mp3"));//30ms
long end=System.currentTimeMillis();
System.out.println(end-start);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

测试文件是

Java输入输出流复制文件所用时间对比

原文链接:http://blog.csdn.net/su20145104009/article/details/52125722