How to Create a New Folder in Java
In Java, we can use the File object to create a new folder or directory. The File class of Java provide a way through which we can make or create a directory or folder. We use the mkdir() method of the File class to create a new folder.
For creating a directory, we first have to create an instance of the File class and pass a parameter to that instance. This parameter is the path of the directory where we need to create it. After that, we have to invoke the mkdir() method using that file object.
Let's use the mkdir() method to create a directory or folder through a Java program.
If we go to that location, we will see the created folder as:
Note: If we enter an unavailable path, the mkdir() method will not create a folder and pass the control flow to the else part.
Creating Hierarchy of new Folders
The drawback of the mkdir() method is resolved by the mkdirs() method. The mkdirs() method is more powerful than mkdir() method. The mkdirs() method creates a hierarchy of new folders or directories. It creates a folder in the same way as the mkdir() method, but it also creates the parent folders too that do not exist.
Let's take an example to understand how the mkdirs() method is different from the mkdir() method.
When we access the desired location, we see the created folder. If the user enters an unavailable location, the mkdirs() make it available by creating all the parent folders that do not exist in the system.