How to create a directory in the current working directory, in Java

What is the shortest way to create a directory called "Foo" under the current working directory of my Java application (if it does not already exist)?

Or a slightly different angle: what is the Java equivalent of Directory.CreateDirectory("Foo") in .NET?

+6
java filesystems
source share
2 answers

The java.io package does not have a Directory class, but instead you can use the mkdir() method in the File class:

 (new File("Foo")).mkdir() 

Note that mkdir() has two separate failure modes:

  • "If there is a security manager and its checkWrite() method does not allow you to create a named directory," then a SecurityException will be thrown.
  • If the operation fails for another reason, mkdir() will return false. (More specifically, it will return true if and only if the directory was created.)

Point 1 is fine - if you do not have permission, quit. Point 2 is a little not optimal for three reasons:

  • You need to check the logical result of this method. If you ignore the result, the operation may fail.
  • If you receive a false return, you do not know why the operation failed, which makes it difficult to recover, or formulate a meaningful error message.
  • The strict wording of the “if and only if” contract also means that the method returns false if the directory already exists.

Also: contrast point 3 with .NET behavior. Directory.CreateDirectory() , which does nothing if the directory exists. This approach makes sense - "create directory"; "ok, directory created." Does it matter whether it was created now or earlier; this process or another? If you really cared that you would not ask another question: "Does this directory exist?"

The next caveat is that mkdir() will not create more than one directory at a time. For my simple example directory called "Foo", this is fine; however, if you want to create a directory called "Bar" in the Foo directory (that is, create a directory "Foo / Bar"), you must remember to use the mkdirs() method.

So, to get around all these caveats, you can use a helper method, for example:

 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."); } 
+7
source share

I saw a slightly more concise form of your createDirectory method:

 File f = new File(xyz); if (!f.exists() && !f.mkdirs()) throw new IOException("Could not create directory " + f); 

It may also be useful to check if f exists, but is not a directory.

+1
source share

All Articles