How to create a directory in project folder using Java?

Java 8Object Oriented ProgrammingProgramming

The class named File of the package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

The mkdir() method of this class creates a directory with the path represented by the current object.

Therefore, to create a directory −

  • Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).

  • Invoke the mkdir() method using the above-created file object.


The following Java example reads the path and name of the directory to be created, from the user, and creates it.

 Live Demo

import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(;
      String path =;
      System.out.println("Enter the name of the desired a directory: ");
      path =;
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdir();
         System.out.println("Directory created successfully");
      } else {
         System.out.println("Sorry couldn’t create specified directory");


Enter the path to create a directory:
Enter the name of the desired a directory:
Directory created successfully

If you verify, you can observe see the created directory as −

But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory.

For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −


Where the test and myDirectories folders don’t exist, the mkdir() method will not create it.

Published on 11-Sep-2019 14:10:53