I/O流实现文件内容复制

Java I/O流实现文件内容复制

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
package com.practice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
/***
* 复制功能
* @author HDC
*/
public class Copy {
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
System.out.println("请输入要复制文件的路径");
String path1 = scn.next();
System.out.println("请输入复制文件的新名字");
String path2 = scn.next();
File f1 = new File(path1);
File f2 = new File(path2);
// 判断文件是否存在
if (!f1.exists()) {
f1.createNewFile();
}
if (!f2.exists()) {
f2.createNewFile();
}
// 创建输入输出流
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] b = new byte[1024];
int len = 0;
// 查看原文件是否有内容,若没有手动输入
if ((len = in.read(b)) == -1) {
System.out.println("源文件为空,请手动输入再复制");
String s = scn.next();
OutputStream out1 = new FileOutputStream(f1);
out1.write(s.getBytes());
out1.flush();
out1.close();
} else {
out.write(b, 0, len);
}
while ((len = in.read(b)) != -1) {
out.flush();
out.write(b, 0, len);
out.flush();
}
System.out.println("复制成功");
in.close();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}