Search code examples
javafilefilenotfoundexceptionaccess-denied

Copying a file results in java.io.FileNotFoundException (Access is Denied) from output


File file1 = new File(file.getAbsoluteFile() + "/example/directory/example.png");
file1.mkdirs();
file1.setWritable(true);
file1.createNewFile();
try {
    FileInputStream is = new FileInputStream(exampleInputDirectory);
    FileOutputStream os = new FileOutputStream(file1);
    FileChannel srcChannel = is.getChannel();
    FileChannel dstChannel = os.getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    is.close();
    os.close();
} catch (IOException e) {
    e.printStackTrace();
}

This is my setup for copying an image file to a new directory tree. However, when this code is executed I get the following:

java.io.FileNotFoundException: *points to output directory* (Access is denied)

Have I gone about creating file1 incorrectly?


Solution

  • The problem here is because of using

    file1.mkdirs();
    

    and

    file1.createNewFile();
    

    together.

    Since the file1 object is already been given 'directory' attributes after creating it as directory by calling "file1.mkdirs()", but then you are again using the same object to create a 'file', that means changin attribute of file1 object from directory to a file, which is not allowed. that's why its giving you FileNotFound.