赞
踩
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..."); } }
运行时报错信息:
试着切换盘符,切换其他文件夹,以及修改文件夹的只读属性,都没有解决问题,仍然提示“拒绝访问“。
错误原因在这行代码
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 (系统找不到指定的路径。)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。