复制多级文件,将一个文件夹中的所有内容复制到另一个文件夹中。
设计递归方法,通过传入源文件和目的文件,将源文件中内容完全复制到目的文件中:
代码如下:
private static void copyFolder(File srcFile, File destFile) throws IOException { //srcFile为源文件,destFile为目的文件
if (srcFile.isDirectory()) {
File newFolder = new File(destFile, srcFile.getName());
newFolder.mkdir();
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
copyFolder(file, newFolder);
}
} else {
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
定义复制文件的方法:(运用字节缓冲流)
private static void copyFile(File srcFile, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}