Java IO流对多层文件夹的复制问题
package com.Test.A;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* InputStream和OutputStream的复制文件和文件夹问题
*/
public class StreamTest {
public static void main(String[] args) {
File f1 = new File("D:\\ECE");
File f2 = new File("D:\\haha");
copyAllDrictory(f1, f2);
}
public static void copyAllDrictory(File start, File end) {
// 声明输入输出流
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
// 对IO流异常进行处理
try {
// 判断读取是否是文件夹
if (start.exists()) {
if (start.isDirectory()) {
// 遍历文件夹
for (File i : start.listFiles()) {
if (i.isDirectory()) {
System.out.println(i);
File f = new File(end, i.getName());
f.mkdirs();
System.out.println(f);
copyAllDrictory(i, f);
} else {
bufferedInputStream = new BufferedInputStream(new FileInputStream(i));
String endname = i.getName();
bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(new File(end, endname)));
int len = 0;
byte[] bytes = new byte[2048];
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
}
}
} else {
// 不是文件夹
bufferedInputStream = new BufferedInputStream(new FileInputStream(start));
bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(new File(end, start.getName())));
int len = 0;
byte[] bytes = new byte[2048];
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
}
} else {
System.out.println("文件夹路径不正确");
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("文件复制失败,请重试");
} finally {
// 关流
try {
if (bufferedOutputStream != null)
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException("文件复制失败,请重试");
} finally {
try {
if (bufferedInputStream != null)
bufferedInputStream.close();
} catch (IOException e) {
throw new RuntimeException("文件复制失败,请重试");
}
}
}
}
}
若是有工具包工具包优先
commons-io工具类挺好 org.apache.commons.io.FileUtils