How to create a directory programmatically in Java using File class

How to create a directory programmatically in Java using File class:

Java File class i.e. java.io.File is used for file or folder related operations. We can use it to create a directory programmatically using a File class.

Create a new directory using mkdir():

mkdir() method is used to create a new directory and this method is defined in File class. For that, we need to create a File object by passing the path of the directory. Then, we can call mkdir() on this object to create a new directory on that path.

It returns one boolean value, true if the directory is created successfully, else false.

Java program:

Let’s take a look at the below program:

import java.io.File;

public class Main {

    public static void main(String[] args) {
        String path = "/Users/cvc/Downloads/test/sample-dir";

        File file = new File(path);

        boolean result = file.mkdir();

        if (result) {
            System.out.println("Directory created successfully !!");
        } else {
            System.out.println("Directory creation failed !!");
        }
    }
}

If you run this program, it will create a directory in the provided path.

The return value of mkdir is stored in result. Based on its value, it is printing the message.

You might also like: