How to create directories (hierarchically) in Java?


Since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files.

The createDirectories() method creates the given directory including the non-existing parent directory.

Example

Live Demo

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Demo {
   public static void main(String args[]) throws IOException {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String pathStr = sc.next();      
      System.out.println("Enter the required directory hierarchy: ");
      pathStr = pathStr+sc.next();      
      //Creating a path object
      Path path = Paths.get(pathStr);      
      //Creating a directory
      Files.createDirectories(path);      
      System.out.println("Directory hierarchy created successfully");
   }
}

Output

Enter the path to create a directory:
D:
Enter the required directory hierarchy:
sample1/sample2/sapmle3/final_directory
Directory hierarchy created successfully

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

You can also create a hierarchy of new directories using the method mkdirs() of the File. This method creates the directory with the path represented by the current object, including non-existing parent directories.

Example

Live Demo

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Demo {
   public static void main(String args[]) throws IOException {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String pathStr = sc.next();    
      System.out.println("Enter the required directory hierarchy: ");
      pathStr = pathStr+sc.next();    
      //Creating a File object
      File file = new File(pathStr);    
      //Creating the directory
      boolean bool = file.mkdirs();    
      if(bool){
          System.out.println("Directory created successfully");      
       }else{
          System.out.println("Sorry couldn't create specified directory");      
       }  
   }
}

Output

Enter the path to create a directory:
D
Enter the required directory hierarchy:
sample1/sample2/sample3/final_directory

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

Updated on: 08-Feb-2021

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements