利用字节流实现文件拷贝

  • FileOutputStream(输出流,写入信息)
  • FileInputStream(输入流,读取信息)

字节流图:

Markdown


代码
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
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.LinkPermission;

public class demo01 {
public static void main(String[] args) {
testCopy();
}

public static void testCopy(){
long start = 0 , end = 0;
start = System.currentTimeMillis();
Copy("test//demo01.txt","test//demo02.txt","test//demo02.txt");
end = System.currentTimeMillis();
System.out.println("完成时间: "+ (end-start)+" ms");
}

public static void Copy(String sourceName, String targetName, String redName){
FileInputStream input = null;
FileInputStream input2 = null;
FileOutputStream output = null;
try {
input = new FileInputStream(sourceName);//读取文件
output = new FileOutputStream(targetName);//写入文件
input2 = new FileInputStream(redName);//读取文件
int lenth = -1;
int lenth2 = -1;
byte[] bytes = new byte[1024];//字节数组来复制,效率更高
while ((lenth = input.read(bytes))>-1){
output.write(bytes);
}
while ((lenth2 = input2.read(bytes))>-1){
String str = new String(bytes);
System.out.println(str);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (input != null)
input.close();
}catch (IOException e){
e.printStackTrace();
}
try {
if (output != null)
output.close();
}catch (IOException e){
e.printStackTrace();
}

}
}
}

步骤
  • 构造->读取->关闭

注意:
  • 一般使用字节数字来读取,效率更高
  • 最后必须要关闭接口,在finally里实现关闭,关闭前需判断是否存在