File.mkdir或mkdirs返回false - 原因? [英] File.mkdir or mkdirs return false - Reason?

查看:5066
本文介绍了File.mkdir或mkdirs返回false - 原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么file.mkdir返回false?

Why file.mkdir is returning false?

Google表示可能有多种原因(例如安全性,权限,路径名等)。

Google indicates that there could be several reasons (e.g. security, permissions, pathname, etc).

我的问题:


  1. 如何找到返回false的确切原因?

  2. 如果安全/权限是一个原因,那么为什么不抛出SecurityException?


推荐答案


如果安全/权限是一个原因,那么为什么不抛出SecurityException(在javadoc中提到)?

If security/permissions is a reason, then why is SecurityException NOT thrown (which is mentioned in javadoc)?

当您没有JVM级别的权限而不是操作系统级别

A SecurityException is thrown when you don't have JVM-level permission to do something, not OS-level


有没有办法找到返回false的确切原因?

Is there a way to find the exact reason why of returning false?

不,AFAIK。知道的唯一方法是自己检查目录的权限,确保它在调用之前不存在,检查父目录是否存在等等。

No, AFAIK. The only way to know would be to check the permissions on the directory yourself, make sure it doesn't exist before calling them, check if the parent directory exists, etc.

但是,如果您使用 Java 7或更高版本,则可以使用NIO来创建目录。具体来说, Files.createDirectory

However, if you're using Java 7 or higher, you can use NIO instead to create the directory. Specifically, Files.createDirectory:

File dir = new File("mydir");
Files.createDirectory(dir.toPath());

如果你想使用 java.io.File完全使用NIO / code>,你可以使用 Paths.get 创建路径而不是:

If you want to use NIO entirely with using java.io.File, you can use Paths.get to create a Path instead:

Path dir = Paths.get("mydir");
Files.createDirectory(dir);

在这两种情况下,如果无法创建目录,它将抛出 IOException ,其中包含操作失败原因的确切原因。

In both cases, if the directory can't be created, it will throw an IOException with an exact reason for why the operation failed.

对于中的大多数方法都是如此文件,建议使用它而不是使用文件类中的方法。

This is true for most of the methods in Files, and so using it is recommended over using the methods in the File class.

这篇关于File.mkdir或mkdirs返回false - 原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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