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

时间:2011-08-17 13:29:59

标签: 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)

2 个答案:

答案 0 :(得分:4)

拒绝访问与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);

答案 1 :(得分:1)

我会将我的文件放在不在用户/...

下的目录中

尝试将您的文件放在c:/ mytest /

相关问题