刚开始一直拒绝访问
Exception in thread “main” java.io.FileNotFoundException: F:\des\test (拒绝访问。)
经过一步步调试
在copyFolder
函数的else
中判断出是文件后
File newFile = new File(desFolder,srcFolder.getName());
copyFile(desFolder, newFile);
应该更改为
copyFile(newFile, resource);
意思是:将当resource源文件复制到newFile的绝对路径
例如:将D:\test\a.java
复制到F:\test\
中
newFile:F:\test\a.java
resource:D:\test\a.java
由此解决了目标目录拒绝访问的问题
艹,害我找了半天bug找不出来,还是一步步断点调试发现问题
import java.io.*;
//复制源文件每个文件夹里的.png文件并创建同名文件夹到目标目录下
/*
1、封装源文件夹
2、封装目标文件夹
3、调用复制文件夹函数
判断:是一个文件夹,则在目标目录下创建一个同名文件夹
获取所有文件,递归该函数
是一个png文件,封装一个新文件对象,直接复制到目标文件夹中(调用复制文件夹函数)
写出复制文件函数
使用字节流传输(图片是二进制文件)
*/
public class CopyFile {
public static void main(String[] args) throws IOException {
File desFile = new File("D:\\脑图");
File recFile = new File("D:\\基础知识脑图");
copyFolder(recFile, desFile);
}
public static void copyFolder(File resource, File destination) throws IOException {
//如果源文件是个文件夹
if(resource.isDirectory()) {
//在目标文件夹下创建一个新的文件夹
File newFolder = new File(destination, resource.getName());
newFolder.mkdir();
//获取目标文件夹下所有文件
File[] fileList = resource.listFiles();
for(File file : fileList){
copyFolder(file, newFolder);
}
}else{
if (resource.getName().endsWith(".png")) {
File newFile = new File(destination, resource.getName());
copyFile(newFile, resource);
}
}
}
public static void copyFile(File des, File res) throws IOException {
FileInputStream fileInputStream = new FileInputStream(res);
FileOutputStream fileOutputStream = new FileOutputStream(des);
int b = 0;
byte[] buff = new byte[1024];
while((b = fileInputStream.read(buff)) != -1){
fileOutputStream.write(buff,0,b);
}
fileInputStream.close();
fileOutputStream.close();
}
}