java递归创建目录


import java.io.File;

public class CreateDirectory {

    public static void main(String[] args) {
        String path = "D:\\heap\\d\\c\\e";
        createDirectory(path);
    }

    public static void createDirectory(String path) {
        File file = new File(path);

        // 如果该文件夹存在,直接返回
        if (file.exists()) {
            return;
        }

        // 检查上一级路径是否存在,如果不存在则递归创建
        File parent = file.getParentFile();
        if (!parent.exists()) {
            createDirectory(parent.getPath());
        }

        // 创建当前目录
        boolean result = file.mkdir();
        if (result) {
            System.out.println("成功创建目录:" + path);
        } else {
            System.out.println("创建目录失败:" + path);
        }
    }
}


posted on 2023-06-20 23:21  x-cuke  阅读(422)  评论(0)    收藏  举报