Home »
Java programming language
Java File Class boolean mkdir() method with Example
Java File Class boolean mkdir() method: Here, we are going to learn about the boolean mkdir() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 14, 2019
File Class boolean mkdir()
- This method is available in package java.io.File.mkdir().
- This method is used to create a new directory by using mkdir() method and this method is accessible with the File object.
- If a directory already exists i.e the name of the created directory already exists that means we are not allowed to create a directory of the same name.
- The return type of this method is Boolean i.e. it returns true or false if true that means directory is successfully created and returns false that means the directory already exists.
Syntax:
boolean mkdir(){
}
Parameter(s):
We don't pass any object as a parameter in the method of the File.
Return value:
The return type of this method is boolean, it returns either true or false – if the directory created successfully it returns true otherwise it return false.
Java program to demonstrate example of mkdir() method
// import the File class because we will use File class methods
import java.io.File;
// import the Exception class because it may raise an
// exception when working with files
import java.lang.Exception;
public class CreateDirectory {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
File dir1 = new File("E:\\Java");
File dir2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles");
// By using mkdir()create a new directory named
// C:\\Users\\Articles because directory is not
// exists (i.e it returns true) so this method
// creates empty directory.
if (dir1.mkdir())
System.out.println("Directory created Successfully" + " " + dir1.getName() + " ");
else
System.out.println("Directory already exists " + dir1.getName());
// By using mkdir() is not create a new directory named
// " C:\\Users\\computer clinic\\OneDrive\\Articles "
// because the name of this directory is already exists
// (i.e. it returns false) so we will get a message
// Directory already exists .
if (dir2.mkdir())
System.out.println("Directory created Successfully" + dir2.getName());
else
System.out.println("Directory already exists " + " " + dir2.getName());
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
D:\Programs>javac CreateDirectory.java
D:\Programs>java CreateDirectory
Directory created Successfully Java
Directory already exists Articles