Java实现复制文件夹中的文件内容到另一个文件夹中
public static void main(String[] args) throws Exception {
//递归遍历D:/companyFile/TestToExcel1/diesel/shry1文件夹下的文件
test("D:/companyFile/TestToExcel1/diesel/shry1");
}
private static void test(String fileDir) throws Exception {
List<File> fileList = new ArrayList<File>();
File file = new File(fileDir);
// 获取目录下的所有文件或文件夹
File[] files = file.listFiles();
if (files == null) {
return;
}
// 遍历,目录下的所有文件
for (File f : files) {
if (f.isFile()) {
fileList.add(f);
} else if (f.isDirectory()) {
System.out.println(f.getAbsolutePath());
test(f.getAbsolutePath());
}
}
for (File f1 : fileList) {
FileInputStream fis = new FileInputStream(f1);
//将复制的文件输出到E:/copyFile1文件夹
FileOutputStream fos = new FileOutputStream(new File("E:/copyFile1",f1.getName()));
copy(fis, fos);
fis.close();
fos.close();
}
}
public static void copy(InputStream in, OutputStream out) throws Exception {
byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf))!=-1) {
out.write(buf, 0, len);
}
}