在 WIndows 上的 Java 中,我如何检测文件是否具有 'Read Only' 属性
In Java on WIndows how do I detect if file has 'Read Only' attribute
在 Windows 中,文件可能不可写,因为用户由于访问控制列表权限而无权修改文件,或者只是因为文件设置了只读属性。
我的应用程序是用Java写的,这两种情况中的任何一种都可能导致Files.isWritable(file)失败,但是我如何确定是哪种情况导致了失败,具体我只想知道如果设置了只读属性。
我注意到有一个 File.setReadOnly() 方法(以及 File.setWritable()),我假设 Windows 这只会设置属性,但是似乎不是 File.isReadOnly() 方法。
使用canWrite()
方法:
if(file.canWrite()) {
System.out.println("you can write");
} else {
System.out.println("you cannot write");
}
有用信息:
Returns:
true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to
write to the file; false otherwise.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write
access to the file
不要。只需尝试打开文件进行输出。如果它不可写,它将失败。捕获异常然后处理它。不要试图预测未来。您可能会错误地测试它,或者它可能会在测试和使用之间发生变化,这两种方式都是如此。
我使用此方法检查是否只读,(它使用自定义方法 Platform .ifWindows() 仅在 Windows 上 运行,但您可以使用其他方法) .
private boolean isReadOnlyFile(Path file)
{
if(Platform.isWindows())
{
if (!file.toFile().canWrite())
{
DosFileAttributes dosAttr;
try
{
dosAttr = Files.readAttributes(file, DosFileAttributes.class);
if(dosAttr.isReadOnly())
{
return true;
}
}
catch (IOException e)
{
}
}
}
return false;
}
在 Windows 中,文件可能不可写,因为用户由于访问控制列表权限而无权修改文件,或者只是因为文件设置了只读属性。
我的应用程序是用Java写的,这两种情况中的任何一种都可能导致Files.isWritable(file)失败,但是我如何确定是哪种情况导致了失败,具体我只想知道如果设置了只读属性。
我注意到有一个 File.setReadOnly() 方法(以及 File.setWritable()),我假设 Windows 这只会设置属性,但是似乎不是 File.isReadOnly() 方法。
使用canWrite()
方法:
if(file.canWrite()) {
System.out.println("you can write");
} else {
System.out.println("you cannot write");
}
有用信息:
Returns: true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
Throws: SecurityException - If a security manager exists and its
SecurityManager.checkWrite(java.lang.String)
method denies write access to the file
不要。只需尝试打开文件进行输出。如果它不可写,它将失败。捕获异常然后处理它。不要试图预测未来。您可能会错误地测试它,或者它可能会在测试和使用之间发生变化,这两种方式都是如此。
我使用此方法检查是否只读,(它使用自定义方法 Platform .ifWindows() 仅在 Windows 上 运行,但您可以使用其他方法) .
private boolean isReadOnlyFile(Path file)
{
if(Platform.isWindows())
{
if (!file.toFile().canWrite())
{
DosFileAttributes dosAttr;
try
{
dosAttr = Files.readAttributes(file, DosFileAttributes.class);
if(dosAttr.isReadOnly())
{
return true;
}
}
catch (IOException e)
{
}
}
}
return false;
}