我有以下代码片段:
public class ExampleClass {
public static void main(String[] args) throws FileNotFoundException {
String filePath = args[0];
File file = new File(filePath);
if (!file.exists())
throw new FileNotFoundException();
if (file.canWrite())
System.out.println(file.getAbsolutePath() + ": CAN WRITE!!!");
else
System.out.println(file.getAbsolutePath() + ": CANNOT WRITE!!!!!");
if (file.canRead())
System.out.println(file.getAbsolutePath() + ": CAN READ!!!");
else
System.out.println(file.getAbsolutePath() + ": CANNOT READ!!!!!");
if (file.canExecute())
System.out.println(file.getAbsolutePath() + ": CAN EXECUTE!!!");
else
System.out.println(file.getAbsolutePath() + ": CANNOT EXECUTE!!!!!");
}
}
它在Linux OS 中可以工作,但问题是它在windows7 中不工作。所以问题是:有人知道在 Java OS 中独立检查文件权限的方法吗?
最佳答案
这可能是由某些东西(例如反病毒产品)以不一致的方式“调节”文件访问引起的。
当然,很难相信 Java File.canXxxx()
方法在任何类型的 Windows 上都通常被破坏。
更新 - 我收回这句话。阅读this Sun bug report ......哭泣。简短的回答是这是一个 Windows 错误,Sun 决定不解决它。 (但是新的 Java 7 API确实可以工作...)
FWIW,我认为尝试像这样检查文件访问权限是错误的做法。最好简单地尝试使用该文件,并在异常发生时捕获异常。参见 https://stackoverflow.com/a/6093037/139985对于我的推理。 (现在我们有了另一个原因......)
关于java - 如何在 Java 中检查文件权限(独立于操作系统),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783677/