java - Java : java. io.FileNotFoundException 中的错误:C:\Users\FSSD\Desktop\My Test(访问被拒绝)

标签 java file windows-7 hidden

我有一个 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/

相关文章:

java - 我可以从内部类访问注入(inject)的 ejb 吗?

java - 从非常基础到非常高级的密码学书籍

java - 共享元素转换不起作用,黑屏

regex - 如何删除ubuntu双引号中的“字符?

c++ - Qt 文件调整大小在 Linux 中表现怪异

c# - 如何以编程方式检查 Windows 是否是最新的?

eclipse - Pydev "Undefine variable from import"在 Ubuntu 上使用 pygame 而不是 Windows

java - 如何使用 apache-commons-io FileUtils.listFilesAndDirs 过滤某个目录的所有目录和子目录?

java - File.delete() 是否删除 File 对象的指针?

java - 使用指向多个位置的 JAVA_HOME 吗?