For some reason I keep getting java.nio.file.AccessDeniedException
every time I try to write to a folder on my computer using a java webapp on Tomcat. This folder has permissions set to full control for everyone on my computer (Windows). Does anybody know why I get this exception?
Here's my code:
public void saveDocument(String name, String siteID, byte doc[]) {
try {
Path path = Paths.get(rootDirectory + siteID);
if (Files.exists(path)) {
System.out.println("Exists: " + path.toString());
Files.write(path, doc);
} else {
System.out.println("DOesn't exist");
throw new Exception("Directory for Site with ID " + siteID + "doesn't exist");
}
} catch (FileSystemException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
} catch (IOException e ) {
System.out.println("Exception: " + e);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
And here is the error:
Exception: java.nio.file.AccessDeniedException: C:\safesite_documents\site1 java.nio.file.AccessDeniedException: C:\safesite_documents\site1 at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230) at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:430) at java.nio.file.Files.newOutputStream(Files.java:172) at java.nio.file.Files.write(Files.java:3092)
Possible reason why: See my post on supersuser about how I can't uncheck 'Read Only' for any of my folders on windows 7. Even though all the folders aren't read only to anything but java.
Ok it turns out I was doing something stupid. I hadn't appended the new file name to the path.
I had
rootDirectory = "C:\\safesite_documents"
but it should have been
rootDirectory = "C:\\safesite_documents\\newFile.jpg"
Sorry it was a stupid mistake as always.