This blog will discuss the approaches to creating a directory using Java.
How to Create a Directory Using Java?
A directory can be created in java using the following approaches:
Approach 1: Create a Directory in Java Using “File” Object and “mkdir()” Method
The “mkdir()” method is utilized to create a new directory and gives “true” if the directory is created. In the other case, it returns “false”. This method can be applied combined with the “File” object to specify the directory name and path and create a directory at that path:
Apply the following steps as provided in the above lines of code:
- First of all, create a “File” object named “dir” using the “new” keyword and the “File()” constructor, respectively.
- Also, specify the path and the directory name, respectively.
- In the next step, associate the “mkdir()” method with the created object such that upon creating the directory, the “if” condition executes with the stated success message.
- In the other situation, the “else” condition will be invoked.
Output
Creation of Directory
In the above pop-up, it can be observed that the specified directory is created at the allocated path.
Approach 2: Create a Directory in Java Using the “Files.createDirectories()” Method
The “createDirectories()” method makes a new directory. Moreover, it also creates parent directories if they do not exist. The “get()” method of the “Path” class transforms a path string into a “Path” instance. These approaches can be applied in combination to specify the path and directory name and create a directory at that path:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public static void main(String[] args) throws IOException{
String dirName = "/JavaDirectory";
Path dirpath = Paths.get(dirName);
Files.createDirectories(dirpath);
System.out.println("The Directory is created successfully!");
}
In this code block:
- The “IOException” is thrown to cope with the “I/O” limitations.
- In the next step, specify the path and the directory name, i.e., “JavaDirectory”.
- Note that single or multiple parent directories can also be created using this approach, i.e., ParentDirectory/JavaDirectory.
- After that, associate the “get()” method with the “Paths” class to fetch the “Path” instance.
- Lastly, apply the “Files.createDirectories()” method to create the directory at the specified path and display the success message upon creation.
Output
Creation of Directory
In this outcome, it is evident that the specified directory is created appropriately.
Conclusion
A directory can be created in Java using the combined “File” object and “mkdir()” method or the “Files.createDirectories()” method. These approaches can be applied to create single or multiple directories(parent->child) in accordance with the specified name and path. This blog elaborated on the approaches to creating a directory using Java.