How do I create a new directory in Java?

We create a directory by calling mkdir() method of the File object. This method returns true if and only if the directory was successfully created. If false was returned, no directory is created. This could be caused, for example that the directory was already exists.

package org.kodejava.example.io;

import java.io.File;

public class CreateDirectoryExample {
    public static void main(String[] args) {
        File file = new File("tmpdir");

        if (file.mkdir()) {
            System.out.println("Directory = " + file.getAbsolutePath() + ".");
        } else {
            System.out.println("No directory was created.");
        }
    }
}

Here is the result of the program:

Directory = C:\Users\wsaryada\Documents\Projects\kodejava.project\tmpdir.

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.