Question

my code writes to a file, I am getting access denied error while writing to the file.

Files.write(path, myString.getBytes());

The exception is as fallows

FAILED to write to file.
java.nio.file.AccessDeniedException: 
    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:229)
    at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:430)
    at java.nio.file.Files.newOutputStream(Files.java:170)
    at java.nio.file.Files.write(Files.java:3058)
Was it helpful?

Solution

Sorry, this is not a complete answer but it did not fit in a comment on the question. I hope it helps.

From https://superuser.com/questions/342276/cannot-save-in-hard-disk-drive-c

Since Windows XP, the root directory of the system partition cannot be written to without administrator privileges. However, for security reasons, Windows Vista and Windows 7 do not grant administrator permissions by default even if logged on as an administrator unless explicitly elevated to this privilege level, which may require that you click through a UAC prompt.

Since you are not trying to write to the root of C:\, I don't think it is a permission problem, so perhaps another application has a lock on the file. Did you open the .txt in another application (e.g. Notepad)?

One way to check open file handles is using Process Explorer. You can use Ctrl+F and search for the full path or name of the file and Process Explorer will list all the processes that have an open handle to the file. You can view all the handles for any application using Ctrl+H and even close handles from here. Note: If you get an access denied permission when closing a handle, select File → Show Details for all Processes and try again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top