How to create a directory hierarchy using Java?

JavaObject Oriented ProgrammingProgramming

The class named File of the java.io 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.

Creating directory hierarchy

To create a hierarchy of new directories you can using the method mkdirs() of the same class. 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.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(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdirs();
      if(bool) {
         System.out.println("Directory created successfully");
      }else {
         System.out.println("Sorry couldnt create specified directory");
      }
   }
}

Output

Enter the path to create a directory:
D:\test\myDirectories\
Enter the name of the desired a directory:
sample_directory
Directory created successfully

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

raja
Published on 15-Oct-2019 07:45:54
Advertisements