在Java中,可以使用File類的mkdir()方法或mkdirs()方法來創(chuàng)建目錄。具體方法如下:
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()方法創(chuàng)建目錄,其中mkdir()方法用于創(chuàng)建單級(jí)目錄,而mkdirs()方法用于創(chuàng)建多級(jí)目錄。 在創(chuàng)建目錄之前,可以使用exists()方法檢查目錄是否已經(jīng)存在。