Tests whether a file is writable. This method checks that a file exists and that this Java virtual machine has
appropriate privileges that woul
If file is not writable then attempting to write to that file will throw exception.
package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.DosFileAttributeView;
public class IsWritableExample3 {
public static void main(String... args) throws IOException {
Path tempFile = Files.createTempFile("test-file", ".txt");
//on windows
DosFileAttributeView fileAttributeView =
Files.getFileAttributeView(tempFile, DosFileAttributeView.class);
fileAttributeView.setReadOnly(true);
//create new Path
Files.write(tempFile, "some content...".getBytes());
}
}
Output
Caused by: java.nio.file.AccessDeniedException: C:\Users\Joe\AppData\Local\Temp\test-file16696522405727936981.txt
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
at java.base/java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
at java.base/java.nio.file.Files.newOutputStream(Files.java:218)
at java.base/java.nio.file.Files.write(Files.java:3352)
at com.logicbig.example.files.IsWritableExample3.main(IsWritableExample3.java:24)
... 6 more