This post will discuss how to create a directory in Java, including all non-existent parent directories.

1. Using File#mkdirs() method

The standard solution to create a directory is using the mkdir() method from the File class. It returns true if the directory is created; false otherwise. The invocation for this method would look like below:

Download Code

 
Note that the mkdir() method is useful for creating a single directory. If you want to create a folder hierarchy, you should use the mkdirs() method instead. It creates the directory named by the abstract pathname, including any non-existent parent directories.

 
For example, the following code creates the parent directory named path (if non-existent), followed by its subdirectory dir.

Download Code

2. Using Files.createDirectories() method

With Java 7, you can use the createDirectory() method of the Files class to create a new directory. It throws FileAlreadyExistsException if the directory already exists and IOException if the parent directory does not exist.

Download Code

 
With Java 8, you should use the Files.createDirectories() method that creates a new directory by creating all non-existent parent directories first. This method does not throw an exception if the directory already exists.

Download Code

3. Using FileUtils.forceMkdir() method

Apache Commons IO also provides several utility methods for working with files. To construct a directory, including any necessary but non-existent parent directories, you can use the FileUtils.forceMkdir() method. It throws IOException if the file already exists but is not a directory.

Download Code

That’s all about creating a directory in Java.