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