我有一个 java 代码,用于将文件从一个文件夹复制到另一个文件夹。我使用了如下代码(我使用的是Windows 7操作系统),
CopyingFolder.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyingFolder {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File infile=new File("C:\\Users\\FSSD\\Desktop\\My Test");
File opfile=new File("C:\\Users\\FSSD\\Desktop\\OutPut");
try {
copyFile(infile,opfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyFile(File sourceFile, File destFile)
throws IOException {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
当我使用上面的代码时,出现了以下错误。为什么会生起?我该如何解决?
java.io.FileNotFoundException: C:\Users\FSSD\Desktop\My Test (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at CopyingFolder.copyFile(CopyingFolder.java:34)
at CopyingFolder.main(CopyingFolder.java:18)
最佳答案
拒绝访问与 User Account Control 有关.基本上,您正在尝试读取您没有读取权限的文件(请参阅文件属性下的文件权限)。
您可以通过 File.canRead()
方法查看文件是否可读。
if (infile.canRead()) {
//We can read from it.
}
要将其设置为可读,请使用 File.setReadable(true)
方法。
if (!infile.canRead()) {
infile.setReadable(true);
}
或者您可以使用 java.io.FilePermission
提供文件读取权限。
FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", "read");
或者
FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", FilePermission.READ);
关于java - Java : java. io.FileNotFoundException 中的错误:C:\Users\FSSD\Desktop\My Test(访问被拒绝),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7093683/