关于IO流文件复制时出现"X:/xxx"无法访问的异常情况解决方法

关于IO流文件复制时出现"X:/xxx"无法访问的情况

关于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());

输出流必须获取文件夹下面的文件名称,才能够进行赋值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值