分析:运用递归方法将该目录下所有文件以及目录遍历出来,然后调用创建文件方法创建文件。
代码如下:
package com.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyAllFiles {
/**
* 拷贝指定目录下的所有文件以及目录
*/
public static void main(String[] args) {
File file = new File("e:\\文件夹一");
listAll("f:\\文件夹一\\", file);
}
private static void listAll(String destDir, File file) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
// 如果是目录,则递归向下继续寻找
listAll(destDir + files[i].getName() + "\\", files[i]);
} else {
// 如果是文件,则开始拷贝
copyFile(destDir, files[i]);
}
}
}
private static void copyFile(String destDir, File file) {
File fileDir = new File(destDir);
// 创建目录
if (!fileDir.exists()) {
fileDir.mkdirs();
}
if (file == null) {
return;
}
// 拷贝文件
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(destDir + file.getName());
int ch = -1;
byte[] buf = new byte[1024];
while ((ch = fis.read(buf)) != -1) {
fos.write(buf, 0, ch);
fos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}