开发者

Error in Java : java.io.FileNotFoundException: C:\Users\FSSD\Desktop\My Test (Access is denied)

I have a java code for copy file from one folder to another folder. I used the following code (I used Windows 7 operating system),

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

}

}

While I'm using the above code I got the following Error. Why it will arise? how can I resolved it?

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)


Access Denied has to do with User Account Control. Basically, you're trying to read a file which you don't have permission to read (see the file permission under File properties).

You can see if the file is readable by doing File.canRead() method.

if (infile.canRead()) {
    //We can read from it.

}

To set it to readable, use the File.setReadable(true) method.

if (!infile.canRead()) {
   infile.setReadable(true);
}

Alternatively you can use java.io.FilePermission to provide file read permission.

FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", "read");

Or

FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", FilePermission.READ);


I would put my files in a directory that is not under user/...

Try to put your files in c:/mytest/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜