gpt4 book ai didi

java - 在 java.nio2 中将路径设置为只读的正确方法

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:46 24 4
gpt4 key购买 nike

我很困惑……根据this Java page File.setReadOnly()函数现在是一个“遗留”函数,应该被 Files.setAttribute() 取代...但这需要您知道您使用的是 DOS 还是 POSIX 文件系统。我只想以与平台无关的方式将文件设为只读。我应该怎么做?

最佳答案

我相信 Oracle 只是根据新的 java.nio.file API 将它们称为“遗留”。如果他们真的想阻止它的使用,他们就会弃用这些方法。

但是如果您仍然想使用 NIO2,比如为了保持一致性,您可以查询平台的底层 FileStore 以获取 DOSPOSIX 属性支持。

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

还有 FileAttributeView 类,您可以使用它们轻松地更新多个属性。

DosFileAttributeView attrs =
Files.getFileAttributeView(
file, DosFileAttributeView.class);
attrs.setSystem(true);
attrs.setHidden(true);
attrs.setReadOnly(true);

关于java - 在 java.nio2 中将路径设置为只读的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com