java检查不存在文件的权限
我想做类似的事情:
if (!file.canWrite())
throw Exception("Permission denied");
file.mkdirs();
但是,我不能这样做,因为 canWrite
仅适用于已经存在的文件。有没有办法判断我是否能够写入文件(如果存在)?
编辑:谢谢,我意识到我可以检查该文件是否存在。阅读第三行代码的人将会意识到,我的问题是,如果 mkdirs
无法创建目录,它只会返回 false
- 没有解释原因创建失败。
此外,mkdirs
将创建任意深度嵌套的文件。所以我需要这样的东西:
while(file.hasParent()){
file = file.parent();
if (!file.canWrite()) throw (..);
}
正如保罗指出的,我也需要知道 umask。
I want to do something like:
if (!file.canWrite())
throw Exception("Permission denied");
file.mkdirs();
However, I can't do this because canWrite
only works for files which already exist. Is there a way to tell if I would be able to write to a file, if it existed?
EDIT: Thank you, I realize I could check if the file exists. As those of you who read the third line of code will realize, my problem is that mkdirs
will simply return false
if it couldn't create the directory - no explanation of why creation failed.
Additionally, mkdirs
will create files nested arbitrarily deeply. So I'd need something like:
while(file.hasParent()){
file = file.parent();
if (!file.canWrite()) throw (..);
}
As Paul pointed out, I would need to know the umask too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
做同样的事情,但是在目录上。目录写入权限规定谁可以或不可以将文件写入该目录。
Do the same thing, but on the directory instead. The directory write permissions dictate who can and can't write a file to that directory.
您可以先检查该文件是否存在:
You can first check if the file exists:
您无法测试不存在的内容的权限。但是,您可以进行测试以查看该项目是否存在,如果存在,则检查权限。
You can't test permissions on something that doesn't exist. You can however do a test to see if the item exists and if so then check the permissions.