在学习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)
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();
}
}