java

How to create a directory if it does not exist in Java

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

You can use the Java File class to create directories if they don’t already exist. The File class contains the mkdir() and mkdirs() method.

The mkdir() method creates a single directory if it does not already exist. Here is an example of creating a single directory using the Java File class:
 

 

How to create a directory if it does not exist in Java
import java.io.File;

public class Main {

  public static void main (String args[]) {

		File directory = new File("C:\\Users\\Pc\\Desktop\\NewFolder"); 
		boolean res = directory.mkdir();
		
		if(res) {
		  System.out.println("The directory has been created.");
		}
		else {
		  System.out.println("The directory already exists.");
		}
  }
}

Output:

The directory has been created.

The above code will create a folder named “NewFolder”. mkdir() returns true if the directory has been created, otherwise false.
 
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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