I'm confused... according to this Java page the File.setReadOnly()
function is now a "legacy" function and should be replaced by Files.setAttribute()
... but this requires you to know whether you are working with a DOS or a POSIX filesystem. I just want to make a file read-only, in a platform-independent manner. How should I do it?
I believe Oracle is only calling them "legacy" in light of the new java.nio.file API. If they truly wanted to discourage its usage they would have deprecated those methods.
But if you would still like to use NIO2, say for the sake of consistency, you can query the platform's underlying FileStore
for DOS or POSIX attributes support.
Path file = Paths.get("file.txt");
// Files.createFile(file);
System.out.println(Files.isWritable(file)); // true
// Query file system
FileStore fileStore = Files.getFileStore(file);
if (fileStore.supportsFileAttributeView(DosFileAttributeView.class)) {
// Set read-only
Files.setAttribute(file, "dos:readonly", true);
} else if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) {
// Change permissions
}
System.out.println(Files.isWritable(file)); // false
There are also FileAttributeView
classes that you can use to update multiple attributes easily.
DosFileAttributeView attrs =
Files.getFileAttributeView(
file, DosFileAttributeView.class);
attrs.setSystem(true);
attrs.setHidden(true);
attrs.setReadOnly(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With