在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()方法檢查目錄是否已經存在。