开发者

how can i get the file permission of a directory with java

i try to check the permission granted to a directory in linux, i mean i have a directory with permission 755

berty@berty-laptop:~$ ls -l / |grep directory
drwxr-xr-x   3 root root    4096 2011-01-10 12:33 directory

how can i read that permission with java? I've tried using FilePermission but though i have a directory with all the permissions (777) the FilePermission class always returns an exception

java.securi开发者_如何学运维ty.AccessControlException: Access denied (java.io.FilePermission /home/directory read)
 at java.security.AccessController.checkPermission(AccessController.java:103)
 at com.snippets.Check4DirectoryPermission.checker(Check4DirectoryPermission.java:50)
 at com.snippets.Check4DirectoryPermission.main(Check4DirectoryPermission.java:70)

is there another way to do this?


java.io.File.canRead(), where the file instance is the one representing the dir

Returns: true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise


I think you made a mistake: The ls command shows the existence of /directory, but the Java code complaints about /home/directory - which does not exist unless you have a user called directory.

From your stack trace, I assume that you are creating a FilePermission object yourself and hand it over to AccessController.checkPermission(). This is not how it is used - the FilePermission class does NOT represent the filesystem permissions and does NOT check them. It is used by Java's SecurityManager only, e.g. it looks whether the policy file contains rules that allow the application to access the file. Whether the local file system supports permissions or not is not its concern.

As Bozho suggest, you create a java.io.File() object and use the canXXX() methods to check whether you can access the folder or file.

If you need more detailed information about filesystem-level permissions on a file, you need to wait for Java 7. See the Java NIO.2 Tutorial especially the java.nio.file.attributepackage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜