话不多说先看问题:
问题描述:
public class FileNotFoundException extends IOException
FileNotFoundException 继承于IOException(读写异常)
FileNotFoundException :指示尝试打开由指定路径名表示的文件失败。
场景在线:
使用字节缓冲流复制单继文件夹中的文件:
package 复制单级文件夹;
import java.io.*;
public class demo1 {
public static void main(String[] args) throws IOException {
//1、创键数据源源File对象
File data_source=new File("D:\\Java\\code");
//2、获取数据源对象的File对象名称
String source_name = data_source.getName();
//3、创键目标源File对象
File target=new File("File",source_name);
//4、判断目标文件是否存在,不存在则创键,存在则跳过
if(!target.exists()){
target.mkdir();
}
//5、获取数据源下的所有文件
File[] files = data_source.listFiles();
//6、获取files的文件名称
for(File f:files){
String file_name = f.getName();
File fina=new File(target,file_name);//创键目标源文件路径是target路径拼接数据源文件名;
copy(data_source,fina);//创键函数使用字节缓冲流从数据源中复制文件至目标文件中
/*
* 参数解析:
* 1、f:(D:\Java\code\aa.jpg) 数据源文件
* 2、fina:(File\code\aa.jpg) 目标文件
*/
}
}
private static void copy(File f, File re) throws IOException {
//创键字节缓冲输入流对象————读取数据
BufferedInputStream r=new BufferedInputStream(new FileInputStream(f));
//创键字节缓冲输出流对象————写数据
BufferedOutputStream w=new BufferedOutputStream(new FileOutputStream(re));
//利用字节数据的方式读取数据
byte[] c=new byte[1024];
int len;
while ((len=r.read(c))!=-1){
w.write(c,0,len);
w.flush();//刷新
}
//释放资源
w.close();
r.close();
}
}
解决方案:
请将目标锁定在copy参数的位置:
将两个参数打印出来:
data_source:
fina:
发现问题:数据源路径并没有指向文件
打印数据源文件数组:
成功解决:将copy的参数data_source改为f
如果你还存在疑惑欢迎私信。