Java Create Directory

Profile picture for user arilio666

To create a directory in Java, use the java.io.File class's mkdir() or mkdirs() methods.

package week1.day2;
import java.io.File;
public class Calculator {
    public static void main(String[] args) throws Exception {
        String dirName = "C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\TestDir";
        File directory = new File(dirName);
        boolean success = directory.mkdir();
        if (success) {
            System.out.println("Directory created successfully!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }
}
  • We create a File object to represent the directory we want to create and then use the mkdir() method to create it.
  • If the directory is successfully created, the method returns true, and a success message is printed.
  • If the directory exists or cannot be created, the method returns false, and an error message is printed.
  • Instead of mkdir(), you can use mkdirs() to create the directory and any necessary parent directories that do not exist.
  • The mkdirs() method constructs the whole directory path specified in the File object, including any required parent directories.
Tags