[英]How do I create a directory within the current working directory, in Java
What is the most succinct way to create a directory called "Foo" underneath the current working directory of my Java application (if it does not already exist)? 在我的Java应用程序的当前工作目录下创建名为“Foo”的目录的最简洁方法是什么(如果它还不存在)?
Or, a slightly different angle: What is the Java equivalent of Directory.CreateDirectory("Foo")
in .NET? 或者,稍微不同的角度:.NET中的Directory.CreateDirectory("Foo")
的Java等价物是什么?
The java.io package does not have a Directory
class, but you can use the mkdir()
method on the File
class instead: java.io包没有Directory
类,但您可以在File
类上使用mkdir()
方法:
(new File("Foo")).mkdir()
Note that mkdir()
has two separate failure modes: 请注意, mkdir()
有两种不同的故障模式:
checkWrite()
method does not permit the named directory to be created" then a SecurityException
will be thrown. “如果存在安全管理器且其checkWrite()
方法不允许创建命名目录,则会抛出SecurityException
。 mkdir()
will return false. 如果操作由于其他原因而失败,则mkdir()
将返回false。 (More specifically, it will return true if and only if the directory was created.) (更具体地说, 当且仅当目录已创建时,它才会返回true。) Point 1 is ok — if you don't have permission, throw. 第1点没问题 - 如果您没有权限,请抛出。 Point 2 is a little sub-optimal for three reasons: 由于三个原因,第2点略微次优:
Aside: Contrast Point 3 with the behaviour of the .NET
Directory.CreateDirectory()
which does nothing if the directory exists. 旁白:对比点3与.NETDirectory.CreateDirectory()
的行为,如果该目录存在,它不执行任何操作。 This kind of makes sense — "create a directory"; 这种意义 - “创建一个目录”; "ok, the directory is created". “好的,目录已创建”。 Does it matter if it was created now or earlier; 它是现在还是更早创建的是否重要; by this process or another? 通过这个过程或另一个? If you really cared about that wouldn't you be asking a different question: "Does this directory exist?" 如果你真的很关心那就不会问一个不同的问题:“这个目录是否存在?”
The next caveat is that mkdir()
will not create more than one directory at a time. 下一个警告是mkdir()
不会创建多个目录。 For my simple example of a directory named "Foo" this is fine; 对于我名为“Foo”的目录的简单示例,这很好; however, if you wanted to create a directory called Bar within the directory Foo (ie to create the directory "Foo/Bar") you must remember to use the mkdirs()
method instead. 但是,如果你想在目录Foo中创建一个名为Bar的目录(即创建目录“Foo / Bar”),你必须记住使用mkdirs()
方法。
So to work around all of these caveats, you can employ a helper method such as the following: 因此,要解决所有这些警告,您可以使用辅助方法,如下所示:
public static File createDirectory(String directoryPath) throws IOException {
File dir = new File(directoryPath);
if (dir.exists()) {
return dir;
}
if (dir.mkdirs()) {
return dir;
}
throw new IOException("Failed to create directory '" + dir.getAbsolutePath() + "' for an unknown reason.");
}
I've seen a slightly more concise form of your createDirectory
method: 我已经看到了createDirectory
方法稍微简洁的形式:
File f = new File(xyz);
if (!f.exists() && !f.mkdirs()) throw new IOException("Could not create directory " + f);
It might also be worthwhile to check if f
exists but is not a directory. 检查f
存在但不是目录也可能是值得的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.