关于IO流在复制文件时出现java.io.FileNotFoundException: D:\xxx(拒绝访问。)
拒绝访问的问题
一开始在进行文件复制,程序运行的时候,总是会报出该异常,我一直认为是和文件的读写模式或者只读模式有关,再不济也是和工具的管理员权限有关
在多次调整的情况下发现,并不是该问题的解决方法。
于是在代码上找到了问题的解决方法,原来IO流在文件复制的时候,能够访问的只能是一个文件,而不能访问一个文件夹,报出异常的原因也在这里。
错误代码
public class MovCopy {
public static void main(String[] args) {
File file = new File("D:/视频");
find(file);
}
public static void find(File dir) {
if (dir == null || !dir.exists()) {
return;
}
if (dir.isFile()) {
copy(dir);
}else if(dir.isDirectory()) {
File[] listFiles = dir.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
if (file.isFile()) {
copy(file);
} else if(file.isDirectory()){
find(file);
}
}
}
}
}
public static void copy(File file) {
try(
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("D:/abc" );//出现问题的位置
) {
int count = -1;
byte[] b = new byte[1024];
while((count = fis.read(b)) != -1) {
fos.write(b, 0, count);
}
System.out.println("写出成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
正确代码演示
public static void copy(File file) {
try(
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("D:/abc" + File.separator + file.getName());
) {
int count = -1;
byte[] b = new byte[1024];
while((count = fis.read(b)) != -1) {
fos.write(b, 0, count);
}
System.out.println("写出成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
FileOutputStream fos = new FileOutputStream(“D:/abc” + File.separator + file.getName());
输出流必须获取文件夹下面的文件名称,才能够进行赋值。