How to create Directories using the File utility methods in Java?


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

The createDirectory() method of the Files class accepts the path of the required directory and creates a new directory.

Example

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

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 Test {
   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 name of the desired a directory: ");
      pathStr = pathStr+sc.next();      
      //Creating a path object
      Path path = Paths.get(pathStr);      
      //Creating a directory
      Files.createDirectory(path);      
      System.out.println("Directory created successfully");
   }
}

Output

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

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

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 Test {
   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 name of the desired a directory: ");
      pathStr = pathStr+sc.next();      
      //Creating a path object
      Path path = Paths.get(pathStr);      
      //Creating a directory
      Files.createDirectories(path);      
      System.out.println("Directories created successfully");  
   }
}

Output

Enter the path to create a directory:
D:
Enter the name of the desired a directory:
sample/test1/test2/test3/final_folder
Directory created successfully

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

Updated on: 08-Feb-2021

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements