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

25 comments on “How to create directory in Java

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

    Reply
  2. Code snippet 1.3, do you mean:

    Path path = Paths.get(dir);

    instead of:

    Path path = Paths.get(file);

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

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

        Reply
  4. 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

    Reply
    1. You need to put the code inside the web server.

      Reply
      1. 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.

        Reply
  5. 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!");
    }
    }

    Reply
    1. Thanks for your feedback, we updated the article with more examples.

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

    Reply
  7. 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.

    Reply
  8. 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 😉

    Reply
    1. Thanks for your feedback. We updated the article, the feedback is irrelevant now.

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

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

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

    Reply

Leave a Comment

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