Skip to content

Java create directory example

Java create directory example shows how to create a directory in Java. The example also shows how to create directories including all parent directories or folders.

How to create a directory in Java?

Java File class provides two methods mkdir and mkdirs which can be used to create directories.

This method creates a directory denoted by the file object. It returns true if the directory was created successfully, false otherwise.

Java Create Directory Example


If you re-run the same program, the output will be “Failed to create directory” because the directory was already created in the first run.

How to create all required directories including non-existent parent directories?

Consider the following code.

If dir_1 does not exist, the above-given code will fail to create the dir_2. If you want to create all directories including non-existent parent directories, use the mkdirs method instead of the mkdir method.



Is it necessary to check if a directory exists before creating it?

You might think that it would be a good idea to check if the directory exists before actually creating it using the exists method like given below.

The above-given code calls the mkdir method only if the directory does not exist. Here a call to the exists method is not necessary because mkdir returns true if and only if the directory was created successfully. So even if the directory exists, the mkdir method will not cause any harm neither it will throw any exceptions.

How to create directories using Java 7 NIO?

If you are using JDK 7 or a later version, you can use Paths and Files classes to create directories as given below.

Apache Commons User?

Have a look at the forceMkdir method of the Apache Commons FileUtils class.

This method creates the specified directory along with all the non-existent parent directories. This method may throw IOException in case of failure.

This example is a part of Java File tutorial with examples.

Please let me know your views in the comments section

About the author

Leave a Reply

Your email address will not be published.