java文件操作报错:java.io.FileNotFoundException:D:\..(拒绝访问)

  	import java.io.*;
    
    /**
 	 * @Description: 复制文件,从一个输入流中读取数据,然后通过输出流写入目标位置,一边读一边写
 	 * @ClassName: CopyFile
 	 * @Version: V1.0
 	 */
    public class CopyFile {
    	private static void copy(String src, String target) {
    		File srcFile = new File(src);
    		File targetFile = new File(target);
    		
    		InputStream in = null;
    		OutputStream out = null;
    		try {
    			in = new FileInputStream(srcFile);
    			out = new FileOutputStream(targetFile);
    
    			byte[] b = new byte[1024];
    			int len = -1;
    			while ((len = in.read(b)) != -1) {
    				out.write(b, 0, len);
    			}
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				if (in != null)
    					in.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			try {
    				if (out!= null)
    					out.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	public static void main(String[] args) {
    		String srcPath = "D:\\dva.png";
        	String targetPath = "D:\\dp_work\\temp\\";
        	System.out.println("Start copy...");
        	copy(srcPath, targetPath);
        	System.out.println("End copy...");
    	}
    }

运行时报错信息:
在这里插入图片描述

试着切换盘符,切换其他文件夹,以及修改文件夹的只读属性,都没有解决问题,仍然提示“拒绝访问“。
1
错误原因在这行代码

copy("D:\\dva.jpg", "D:\\dp_work\\temp\\");

FileOutputStream读取流的时候如果是文件夹,就会出错,无论怎么读,都拒绝访问,应该在读取的目录后面加上文件名
代码修改为:

copy("D:\\dva.jpg", "D:\\dp_work\\temp\\dva.jpg");

如果dp_work或temp文件夹不存在,编译时会出现如下提示:
java.io.FileNotFoundException: D:\dp_work\temp\dva.png (系统找不到指定的路径。)

  • 52
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值