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

查看:126
本文介绍了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)?

A SecurityException 当你没有 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,你可以使用Paths.get改为创建 Path:

If you want to use NIO entirely without 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.

这对于 Files 中的大多数方法都是正确的,因此建议使用它而不是使用 File 类中的方法.

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天全站免登陆