How to create directory in Java

In Java, we can use the NIO Files.createDirectory to create a directory or Files.createDirectories to create a directory including all nonexistent parent directories.


  try {

    Path path = Paths.get("/home/mkyong/a/b/c/");

    //java.nio.file.Files;
    Files.createDirectories(path);

    System.out.println("Directory is created!");

  } catch (IOException e) {

    System.err.println("Failed to create directory!" + e.getMessage());

  }

1. Create Directory – Java NIO

1.1 We can use Files.createDirectory to create a directory.

  • If the parent directories not exist, throws NoSuchFileException.
  • If the directory exists, throws FileAlreadyExistsException.
  • If IO errors, throws IOException.

  Path path = Paths.get("/home/mkyong/test2/");
  Files.createDirectory(path);

1.2 We can use Files.createDirectories creates a directory including all nonexistent parent directories.

  • If the parent directories not exist, create it first.
  • If the directory exists, no exception thrown.
  • If IO errors, throws IOException

  Path path = Paths.get("/home/mkyong/test2/test3/test4/");
  Files.createDirectories(path);

1.3 This example uses Files.createDirectories to create a directory /test4/ including all nonexistent parent directories /test2/test3/.

DirectoryCreate1.java

package com.mkyong.io.directory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryCreate1 {

    public static void main(String[] args) {

        String dir = "/home/mkyong/test2/test3/test4/";

        try {

            Path path = Paths.get(file);

            Files.createDirectories(path);

            System.out.println("Directory is created!");

            //Files.createDirectory(path);

        } catch (IOException e) {
            System.err.println("Failed to create directory!" + e.getMessage());
        }

    }
}

2. Create Directory – Legacy IO

For legacy IO java.io.File, the similar methods are file.mkdir() to create a directory, and file.mkdirs() to create a directory including all nonexistent parent directories.

Both file.mkdir() and file.mkdirs() returns a boolean, true if success to create the directory, fail otherwise, no exception thrown.

DirectoryCreate2.java

package com.mkyong.io.directory;

import java.io.File;

public class DirectoryCreate2 {

    public static void main(String[] args) {

        String dir = "/home/mkyong/test2/test3/test4/";

        File file = new File(dir);

        // true if the directory was created, false otherwise
        if (file.mkdirs()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }

    }

}

In legacy IO, the lack of exception thrown in creating directory makes developers very hard to debug or understand why we cannot create a directory, and this is one of the reasons Java releases a new java.nio.Files to throw a proper exception.

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

25 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Bulama Yusuf
5 years ago

Code snippet 1.3, do you mean:

Path path = Paths.get(dir);

instead of:

Path path = Paths.get(file);

Madhumitha
13 years ago

All of your posts are of great help. Thanks. Continue writing more tech posts 🙂

Patrick
8 years ago

How can you create a file on your desktop? (I am using Windows and i am from Germany)

shawn
5 years ago
Reply to  mkyong

how can you reply to someone 18 months after the original post thats terrible. You might as well not have a website.

pravin
13 years ago

i like it but give some video to how to create directory

namrata modha
7 years ago

Very useful.

akshay
12 years ago

Very easy program to create folder at specified path. Thanks

Omar
3 years ago

So useful.

Rafael
5 years ago

How to set the Dir path to choosed Directory with “directoryChooser”
For example a installer, where the user can choose the directory.

Debasish Halder
11 years ago

i want create folder on server like(http://localhost:8084/Test). how to create?
i use this type
File inFile = new File(“http://localhost:8084/Test/web/images”);
boolean b = inFile.mkdir();

its identify that : http:localhost:8084Testwebimeges

shawn
5 years ago
Reply to  mkyong

replying to someone after 4 and half years. Were you in prison or something? Or is it a total lack of professionalism and you just dont care….Unbelievable.

Shilpater
11 years ago

Just a correction:

File files = new File(“C:\Directory2\Sub2\Sub-Sub2”);
if (files.exists()) { <- should be !files.exists()
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}

Binh Thanh Nguyen
12 years ago

Thanks, nice post

sawmon
12 years ago

Hi mr.mkyong.I like your site.Your posts are useful for my java knowledge……

Aforallie
12 years ago

Your examples are great and very helpful. Thank you!

Hafifi
12 years ago

It is just basic example to get you started.
By learning the example you know what library that you need to use.

From there i assume that you will be exploring the library on you own and read the API.

Dariusz
13 years ago

hi
you are missing an exclamation mark in the multiple directories
it should be

File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
	if (<b>!</b>files.exists()) {
		if (files.mkdirs()) {

Could you delete other two posts thanks 😉

Mezbah uddin
13 years ago

Really awesome site for java learner but filling the lackings of the tutorial for javax.swing.Its request to sir consider our demand.

aboulfazl
13 years ago

thanks very much

Shruthi
13 years ago

Very Useful. Thank you very much

anupam ghos
13 years ago

Hi Mkyoung,
Thank you for your posts. These are really helpful.
Regards
Anupam