学习javaSE时觉得挺有意思的记录一下,有报错,但实际已经复制成功,原因还不清楚
package ch01;
import java.io.*;
public class FileCopyTest {
public static void main(String[] args) {
File fileD = new File("D:\\Git\\dev");//拷贝源,拷贝目录
File fileC = new File("C:\\"); //目标路径
copyFile(fileD,fileC); //复制目录的方法
}
private static void copyFile(File fileD, File fileC) { //复制目录的方法
if (fileD.isFile()){//如果是文件写入
FileInputStream in = null; //输入流
FileOutputStream out = null; //输出流
try {
in = new FileInputStream(fileD); //将拷贝的目录放入
String path = (fileC.getAbsolutePath().endsWith("\\") ? fileC.getAbsolutePath() : fileC.getAbsolutePath() + "\\") + fileD.getAbsolutePath().substring(3);//目标目录
out = new FileOutputStream(path);
byte[] bytes = new byte[1024 * 1024];
int count = 0;
while ((count = in.read(bytes)) != -1){
out.write(bytes,0,count);//一次1兆写入(复制)
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
File[] files = fileD.listFiles();
for (File file : files) {
if (file.isDirectory()){
String dirD = fileD.getAbsolutePath();
String dirC = (fileC.getAbsolutePath().endsWith("\\") ? fileC.getAbsolutePath() : fileC.getAbsolutePath() + "\\")+ dirD.substring(3);
File newFile = new File(dirC);
if (!newFile.exists()){//不是文件创建目录
newFile.mkdirs();
}
}
copyFile(file,fileC);//递归调用(关键)
}
}
}