In Java Correct method of setting read-only path in NiO 2
•
Java
I'm confused... According to this Java page file The setreadonly() function is now a "legacy" function and should be called files SetAttribute () replaces... But you need to know whether you are using DOS or POSIX file system I just want to make the file read - only in a platform - independent manner What should I do?
Solution
I believe Oracle is just based on the new Java nio. The file API calls them "legacy." If they really want to stop its use, they will abandon these methods
However, if you still want to use nio2, in order to maintain consistency, you can query the underlying filestore of the platform for DOS or POSIX attribute 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 can be used to easily update multiple attributes
DosFileAttributeView attrs = Files.getFileAttributeView( file,DosFileAttributeView.class); attrs.setSystem(true); attrs.setHidden(true); attrs.setReadOnly(true);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码