IO流复制文件Exception in thread "main" java.io.FileNotFoundException: A (拒绝访问。) 异常


在学习java的时候写了一段程序,利用IO流复制文件。但是运行时出现拒绝访问:
Exception in thread "main" java.io.FileNotFoundException: A (拒绝访问。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at cn.kang01.Mycopy.Mycopying(Mycopy.java:44)
at cn.kang01.Mycopy.main(Mycopy.java:28)

经排查,终于找到原因!IO操作的是文件而不是文件夹,那么我们在写源文件时,就要谨慎。

package cn.kang01;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Mycopy {

	public static void main(String[] args) throws IOException {
		// 封装目录
		File srcfile = new File("A");// 源文件
		File destfile = new File("B");// 目标文件
		// System.out.println(srcfile.getAbsoluteFile());
		// 如果目标文件不存在,就创建
		if (!destfile.exists()) {
			destfile.mkdir();
		}

		File[] f = srcfile.listFiles();// 获得源文件下所有文件路径
		for (File oldfile : f) {
			// System.out.println(n.getName());
			String name = n.getName();// 获得名字
			File newfile = new File(destfile, name);// 创建新的路径(目标路径)
			//System.out.println(newfile);
			Mycopying(oldfile, newfile);//可能很多朋友会出现文件拒绝访问,问题就是出在这里,IO是处理文件而不是文件夹
			
			//我第一次写的时候也是出现拒绝访问,经过排查问题就是Mycopying(sfile, dfile)方法的第一个参数:源文件,
			//有的朋友可能会写成前边封装的srcfile,sfile必须是文件,不能是文件夹;
			//srcfile.listFiles()获得所有文件和子目录,我们可以操作数组的元素。
			
		}

	}

	/**
	 * 复制文件
	 * 
	 * @param sfile
	 *            源文件
	 * @param dfile
	 *            目标文件
	 * @throws IOException
	 */
	public static void Mycopying(File sfile, File dfile) throws IOException {

		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sfile));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dfile));

		byte[] b = new byte[1024];
		int len = 0;
		while ((len = bis.read(b)) != -1) {
			bos.write(len);
			bos.flush();
		}
		bos.close();
		bis.close();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值