在Java中,可以使用File类的mkdir()方法或mkdirs()方法来创建目录。具体方法如下:
import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
String directoryPath = "C:/Users/User/Desktop/NewDirectory";
File directory = new File(directoryPath);
if (!directory.exists()) {
if (directory.mkdir()) {
System.out.println("Directory created successfully!");
} else {
System.out.println("Failed to create directory!");
}
} else {
System.out.println("Directory already exists!");
}
}
}
import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
String directoryPath = "C:/Users/User/Desktop/NewDirectory/SubDirectory1/SubDirectory2";
File directory = new File(directoryPath);
if (!directory.exists()) {
if (directory.mkdirs()) {
System.out.println("Directory created successfully!");
} else {
System.out.println("Failed to create directory!");
}
} else {
System.out.println("Directory already exists!");
}
}
}
以上代码分别使用mkdir()方法和mkdirs()方法创建目录,其中mkdir()方法用于创建单级目录,而mkdirs()方法用于创建多级目录。 在创建目录之前,可以使用exists()方法检查目录是否已经存在。