public static void main(String[] args) throws IOException {
File src = new File("源文件路径");
File dest = new File("目标文件路径");
copyDir(src, dest);
System.out.println("-------------------");
}
private static void copyDir(File src, File dest) throws IOException {
// 在目标文件夹创建原文件夹
File dest_src = new File(dest, src.getName());
dest_src.mkdirs();
// 遍历原文件夹
File[] fileDirs = src.listFiles();
for (File fileDir : fileDirs) {
// 判断是否为文件夹
if (fileDir.isDirectory()) {
copyDir(fileDir, dest_src);
} else if (fileDir.isFile()) {
// 判断是否为文件
File oldFile = fileDir;
File newFile = new File(dest_src, oldFile.getName());
copyFile(oldFile, newFile);
}
}
}
private static void copyFile(File oldFile, File newFile) throws IOException {
FileInputStream in = new FileInputStream(oldFile);
FileOutputStream out = new FileOutputStream(newFile);
int geshu = -1;
byte[] b = new byte[1024];
while ((geshu = in.read(b)) != -1) {
out.write(b, 0, geshu);
out.flush();
}
out.close();
in.close();
} |
|