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.To set it to readable, use the
File.setReadable(true)method.Alternatively you can use
java.io.FilePermissionto provide file read permission.Or