Javatpoint Logo
Javatpoint Logo

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.

How to Create a New Folder in Java

Let's use the mkdir() method to create a directory or folder through a Java program.

CreateFolder.java

Output:

How to Create a New Folder in Java

If we go to that location, we will see the created folder as:

How to Create a New Folder in Java

Note: If we enter an unavailable path, the mkdir() method will not create a folder and pass the control flow to the else part.

How to Create a New Folder in Java

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.

CreateFolderHierarchy.java

Output:

How to Create a New Folder in Java

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.

How to Create a New Folder in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA