Create a directory if it does not exist in Java

In this tutorial, we are going to learn how to create a new directory if it does not exist in Java.

Here is the code for the following program.

import java.io.File;
import java.util.*;

public class New 
{
public static void main(String args[])
{
String DM;
Scanner sc=new ScFCanner(System.in);

System.out.println("Please enter the directory name you want to create");
DM=sc.nextLine();

File file=new File(DM);

if(!file.exists())
{
  if(file.mkdir())
  {
    
  System.out.println("Directory Created");
  }  
}
}
}

Now let’s dissect the program with each step.

  • First, import the util library and I/O library.
  • Create a string that will store the name of the directory (DM).
  • Using the Scanner class we are reading the input from the user,
  • Now, we use the file function to create the instance of the File class through which we’ll invoke the mkdir() function for creating the directory.
  • Since we need to check if the directory already exists, we use if statement to check as shown in the below code.
if(!file.exists())
{
  if(file.mkdir())
  {
    
  System.out.println("Directory Created");
  }
  
}
  • If the directory exists, the If statement will do nothing and if the directory does not exist it will create the directory.

The below output shows that we have run the code twice, the first time it shows the condition satisfied and the second time it does nothing since the directory already exists.

Output:

Please enter the directory name you want to create
Sahil
Directory Created


C:\Users\Sahil\Desktop>javac New.java

C:\Users\Sahil\Desktop>java New
Please enter the directory name you want to create
Sahil

Also read: How to create file / folder explorer with java

Leave a Reply

Your email address will not be published. Required fields are marked *