如何在java中检查目录的写权限? [英] How to check write permissions of a directory in java?

查看:136
本文介绍了如何在java中检查目录的写权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个代码片段,用于检查目录是否具有读/写权限,如果有,则执行某些操作,如果不执行则执行其他操作。我尝试了这里显示的示例:

I would like a code snippet that checks whether a directory has read/write permissions and do something if it does, and does something else if it doesnt. I tried an example shown here:

try {
    AccessController.checkPermission(new FilePermission("/tmp/*", "read,write"));
System.out.println("Good");
    // Has permission
} catch (SecurityException e) {
    // Does not have permission
System.out.println("Bad");
}

问题是异常总是被触发,因此总是打印不管目录是否具有写入权限。 (我将目录chmod到777或000进行测试)。

The problem is the exception is always triggered, so it always ends up printing "Bad" regardless of whether the directory has write permissions or not. (I chmod the directories to 777 or 000 to test).

是否有替代或某种方法可以实现我的需要?

Is there an alternative or some way to accomplish what I need?

推荐答案

如果您只是想检查一下是否可以写:

if you just want to check if you can write:

File f = new File("path");
if(f.canWrite()) {
  // write access
} else {
  // no write access
}

用于检查读取权限,有一个函数 canRead()

for checking read access, there is a function canRead()

这篇关于如何在java中检查目录的写权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆