1 需求
需求1:如果目录不存在新建目录;
需求2:如果目录存在,先删除目录,再新建目录;
2 接口
- File类
- mkdir
- mkdirs
- Files类
- createDirectories
3 示例:File类创建目录
import java.io.File;public class Main {public static void main(String[] args) {try {// 创建一个新的File对象File dir = new File("newDirectory");// 如果目录不存在,则创建它if (!dir.exists()) {dir.mkdir();System.out.println("Directory created successfully!");} else {System.out.println("Directory already exists!");}} catch (Exception e) {e.printStackTrace();}}
}
3.X 示例:Files类创建目录
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class DirectoryCreator {public static void main(String[] args) {// 指定要创建的目录的路径Path directoryPath = Paths.get("path/to/new/directory");try {// 创建目录Files.createDirectories(directoryPath);System.out.println("Directory created successfully.");} catch (IOException e) {System.out.println("An error occurred while creating the directory.");e.printStackTrace();}}
}