Java IO

Java create directory example

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

How to create 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, 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 following code.

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



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

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

The above given code calls mkdir method only if the directory does not exists. Here call to exists method is not necessary because mkdir returns true if and only if the directory was created successfully. So even if the directory exists, 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 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 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.

Have a look at more Java IO examples. Please let us know your views in the comments section below.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *