Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right way to set a Path to readonly in java.nio2

Tags:

java

nio2

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?

like image 271
Jason S Avatar asked Oct 05 '15 16:10

Jason S


1 Answers

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);
like image 186
Ravi K Thapliyal Avatar answered Oct 27 '22 20:10

Ravi K Thapliyal