How to create a directory in Java?

To create a directory in Java, you can use the mkdir() method of the File class. This method creates a new directory with the specified name.

Here is an example of how to create a directory in Java:

import java.io.File;

public class Main {
  public static void main(String[] args) {
    File dir = new File("/tmp/mydir");
    boolean success = dir.mkdir();
    if (success) {
      System.out.println("Directory created successfully");
    } else {
      System.out.println("Error creating directory");
    }
  }
}

This code creates a File object with the name "/tmp/mydir" and then calls the mkdir() method to create a new directory with that name. The mkdir() method returns a boolean value indicating whether the directory was successfully created or not.

You can also use the mkdirs() method to create a directory and all the missing directories in the path leading to it. For example:

File dir = new File("/tmp/mydir/subdir");
boolean success = dir.mkdirs();

This code creates the directory "/tmp/mydir/subdir" and creates the missing directories "/tmp/mydir" and "/tmp" if they don't exist.

It is important to note that the mkdir() and mkdirs() methods will throw a SecurityException if you don't have the necessary permissions to create the directory. You can catch this exception and handle it appropriately.