Home > Software design >  Unable to create FileWriter
Unable to create FileWriter

Time:01-27

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

new FileWriter("C:\\Temp\java_play\\temp")

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

"C:\Temp\java_play\temp (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:\\Temp\java_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.

CodePudding user response:

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:\\Temp\java_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:\Temp\java_play\temp (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
}
  •  Tags:  
  • Related