Skip to content
Advertisement

Unable to create FileWriter

I am trying to create a FileWriter instance pointing to a folder were everyone has write access:

new FileWriter("C:\Tempjava_play\temp")

And I am getting java.io.FileNotFoundException with detail message:

"C:Tempjava_playtemp (Access is denied)"

The folder exists and if I stop in debugger and evaluate expression below it always returns true as it should:

new File("C:\Tempjava_play\temp").canWrite()

I don’t understand what is going on. I am using intelij and I have Windows 7 operating system and I am trying to run this using Java 8.

Thank you in advance.

Advertisement

Answer

You have reported expected behaviour . On Windows any attempt to write to a directory with FileWriter will fail, giving access denied:

File folder = new File("C:\Tempjava_play\temp");
System.out.println("folder.isDirectory()="+folder.isDirectory()+" folder.canWrite()="+folder.canWrite());
// prints "folder.isDirectory()=true folder.canWrite()=true"

System.out.println("new FileWriter("+folder+")="+new FileWriter(folder));
// reports Exception java.io.FileNotFoundException: C:Tempjava_playtemp (Access is denied)

Changing the path to a file within the folder should work fine as long as the filename provided is writable:

File file   = new File(folder, "file"+System.nanoTime()+".xyz");
try(FileWriter fw = new FileWriter(file)) {
   // no exception
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement