使用递归和字节流拷贝(复制)文件夹
思路:
简写说明:
要拷贝的文件/文件夹 -> 源
要拷贝到的地方 -> 目标
1. 如果源是文件,则在目标下创建文件,使用字节流进行读写拷贝。
2. 如果源是文件夹,则在目标下创建文件夹,遍历源下的文件和文件夹;将遍历的元素作为作为源,刚刚创建的文件夹作为目标,传入该方法进行递归操作。
3. 细化处理无法创建,或要创建的文件/文件夹已存在
注:未处理异常
代码如下:
`
public static void main(String[] args) throws IOException {
File des = new File("./day15/copy/");
File src = new File("./day15/src/");
//将src目录拷贝到des目录下
copy(des, src);
}
//递归拷贝之前判断des是否存在,不存在则创建
public static void copy(File des, File src) throws IOException {
//判断目的地是否存在
if (!des.exists()) {
if(!des.mkdirs()) {
System.out.println("无法创建" + des.getAbsolutePath());
return;
}
}else{
copy0(des, src);
}
}
//递归拷贝
private static void copy0(File des, File src) throws IOException {
//目标是文件,无法拷贝
if (des.isFile()) {
System.out.println("目的地是文件,无法拷贝!");
return;
}
String name = src.getName();
File newFile = new File(des, name);
//存在,停止拷贝
if (newFile.exists()) {
System.out.println(des.getAbsolutePath() + "下存在同名文件/文件夹: " + name + ",停止拷贝!");
return;
}
//源是文件
if (src.isFile()) {
//不存在,创建
if(!newFile.createNewFile()) {
System.out.println(des.getAbsolutePath() + "下无法创建文件: " + name + ",停止拷贝!");
return;
}
//开始拷贝
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
//关闭资源
fis.close();
fos.close();
}
//源是目录
if (src.isDirectory()) {
//文件夹不存在,创建
if (!newFile.mkdir()) {
System.out.println(des.getAbsolutePath() + "下无法创建文件夹: " + name + ",停止拷贝!");
return;
}
//遍历源目录下的文件及目录,再次递归
File[] files = src.listFiles();
for (File f : files) {
copy(newFile, f);
}
}
}
`