English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this instance, we will learn how to create directories using Java.
InJava fileThe class provides the mkdir() method to create a new directory. The method returns:
true - If a new directory was created
false - If the directory already exists
import java.io.File; class Main { public static void main(String[] args) { //Create a file object with the specified path File file = new File("Java Example\\directory"); //Attempt to create a new directory ew_directory boolean value = file.mkdir(); if(value) { System.out.println("Create a new directory."); } else { System.out.println("The directory already exists."); } } }
In the above example, we created a file object named file. This object includes information about the specified directory path.
File file = new File("Java Example\\directory");
Here, we used the mkdir() method to create a new directory at the specified path.
If the directory does not exist at the specified location,It will create a new directory and display this message.
Create a new directory.
But if the directory already exists, we will see this message.
The directory already exists.
It is important to note that,DirectoryisJava Examplecreated in the parent directory.
However, ifJava ExampleThe mkdir() method cannot create the directory if the parent directory does not existDirectory.
In this case, we can use the mkdirs() method of the JavaFile class. This method also allows us to create parent directories (if they do not already exist).
import java.io.File; class Main { public static void main(String[] args) { //Create a file object in the current path File file = new File("Java Tutorial\\abc"); //Attempt to create a new directory boolean value = file.mkdirs(); if(value) { System.out.println("Create a new directory."); } else { System.out.println("The directory already exists."); } } }
In the above example, we created a file object named file. This object includes information about the directory path.
File file = new File("Tutorial\\directory");
Here, we used the mkdirs() method to create a new directory with the specified path.
If the directory does not exist at this locationIt will create a new directory and display this message.
Create a new directory.
But if the directory already exists, we will see this message.
The directory already exists.
Here, ifTutorialIf the directory does not exist, the mkdirs() method will also be used withdirectoryTogether createTutorial Directory.
Note: We used it when specifying the path.double backslash. This is because theCharacterIn Java, \ is used asEscape CharacterTherefore, the first backslash is used as an escape character for the second one.