AccessController checkPermission始终抛出异常

时间:2012-07-31 11:34:05

标签: java

如何检查应用程序是否有权读取或写入文件系统上的特定目录。我正在尝试这个:

try {
    AccessController.checkPermission(new FilePermission(files[i]
            .getAbsolutePath(), "read,write"));
}
catch (Exception e) {
    System.out.println(e.toString());
}

但它总是抛出异常和输出:

java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\Dell" "read")
java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\Documents and Settings" "read")
java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\glut-3.7.6" "read")

这里有什么我想念的吗?

2 个答案:

答案 0 :(得分:1)

似乎AccessController在您没有权限时总是会抛出异常。您可以通过捕获SecurityException来处理此问题。

使用java.io.File.canRead()java.io.File.canWrite()方法检查读/写权限的更好解决方案。

答案 1 :(得分:0)

来自文档的文本:

<块引用>
 Determines whether the access request indicated by the
 specified permission should be allowed or denied, based on
 the security policy currently in effect, and the context in
 this object. The request is allowed only if every ProtectionDomain
 in the context implies the permission. Otherwise the request is
 denied.