How to Create a Directory in Java?
In Java, creating a directory is a common operation when working with file system manipulation. Directories are used to organize files and other directories into a hierarchical structure. This article will guide you through the process of creating a directory in Java, providing step-by-step examples and explanations.
Program to Create Current Directory in Java
mkdir() method is available on the File class and attempts to create the specified directory. It only creates the directory itself and throws an exception if any parent directories do not exist.
Below is the implementation of Create Current Directory in Java:
Java
// Java Program to Create Current Directory import java.io.File; // Driver Class public class GFG { // main function public static void main(String[] args) { // Sprecify the Directory Name String directoryName = "My_Learning" ; // Address of Current Directory String currentDirectory = System.getProperty( "user.dir" ); // Specify the path of the directory to be created String directoryPath = currentDirectory + File.separator + directoryName; // Create a File object representing the directory File directory = new File(directoryPath); // Attempt to create the directory boolean directoryCreated = directory.mkdir(); if (directoryCreated) { System.out.println( "Directory created successfully at: " + directoryPath); } else { System.out.println( "Failed to create directory. It may already exist at: " + directoryPath); } } } |
Output:
The created folder can be seen as follows if we go to that location:
Contact Us