right way to set a Path to readonly in java.nio2
Asked Answered
O

1

11

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?

Oversew answered 5/10, 2015 at 16:53 Comment(0)
M
11

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);
Melany answered 5/10, 2015 at 19:5 Comment(3)
Do you happen to know where attributes such as dos:readonly are documented?Delorenzo
Ah, I found them in java.nio.file.attribute.DosFileAttributeView.Delorenzo
Note that using FileStore.supportsFileAttributeView(…) may not give the correct result for non-local file systems; see this answer to my question, Type guarantees for getting DOS file attributes in Java.Delorenzo

© 2022 - 2024 — McMap. All rights reserved.