笔记:
package Test;
import java.io.*;
public class 文件拷贝 {
public static void main(String[] args) throws IOException {
copyFile1("E:\\python.py", "E:\\test.txt"); // 字符数字复制文件
copyFile2("E:\\python.py", "E:\\test.txt"); // 每次读一行复制文件
copyFile3("E:\\Test", "D:\\test1"); // 复制文件夹
}
public static void copyFile1(String s1, String s2) throws IOException {
InputStream is = null; // 源文件
OutputStream os = null; // 目标文件
//读一个字符数组的长度
try {
os = new FileOutputStream(new File(s2));
is = new FileInputStream(new File(s1));
byte[] b = new byte[1024 * 8];
int i;
while ((i = is.read(b)) != -1) {
os.write(b, 0, b.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
os.close();
}
}
private static void copyFile2(String s1, String s2) {
try {
BufferedReader br = new BufferedReader(new FileReader(s1));// 源文件
BufferedWriter bw = new BufferedWriter(new FileWriter(s2));// 目标文件
String str = null;
//每次读一行
while ((str = br.readLine()) != null) {
bw.write(str, 0, str.length());
}
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void copyFile3(String oldPath, String newPath) {
File file = new File(oldPath);
String[] filePath = file.list();
if (!(new File(newPath)).exists()) {
(new File(newPath)).mkdir();
}
for (int i = 0; i < filePath.length; i++) {
if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) {
copyFile3(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
}
if (new File(oldPath + File.separator + filePath[i]).isFile()) {
copyFile2(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
}
}
}
}