In this guide, you will learn about the File mkdir() method in Java programming and how to use it with an example.
1. File mkdir() Method Overview
Definition:
The mkdir() method of the File class is used to create a directory denoted by the abstract pathname of the File object. If the parent directories do not exist, the directory will not be created.
Syntax:
public boolean mkdir()
Parameters:
None.
Key Points:
- The method will create only the directory denoted by the File object's abstract pathname.
- It will return true if and only if the directory was successfully created; false will be returned otherwise.
- If the parent directories do not exist, the directory will not be created.
- No exception is thrown if the directory couldn't be created. Instead, a boolean value is returned to indicate success or failure.
- If a file or directory already exists with the specified name, the directory will not be created.
2. File mkdir() Method Example
import java.io.File;
public class FileMkdirExample {
public static void main(String[] args) {
// Creating a File object for a directory
File directory = new File("path/to/directory/newDirectory");
// Creating the directory
boolean isCreated = directory.mkdir();
if (isCreated) {
System.out.println("Directory was successfully created.");
} else {
System.out.println("Failed to create the directory. It might already exist or its parent directory might not exist.");
}
}
}
Output:
Directory was successfully created. OR Failed to create the directory. It might already exist or its parent directory might not exist.
Explanation:
In the provided example, a File object, directory, is created representing a specific directory.
Invoking the mkdir() method on this object attempts to create the directory denoted by the File object's abstract pathname. If the directory is successfully created, a success message is printed out to the console. If not, a failure message is shown, indicating potential reasons for the failure such as the directory already existing or its parent directory not existing.
Comments
Post a Comment
Leave Comment