在Java 8中,可以使用java.nio.file包来判断目录是否存在并创建目录。

首先,需要导入java.nio.filejava.nio.file.attribute包:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;

然后,可以使用Files.exists()方法来判断目录是否存在:

Path directoryPath = Paths.get("路径/目录名");

if (!Files.exists(directoryPath)) {
    try {
        Files.createDirectory(directoryPath);
        System.out.println("目录已创建");
    } catch (IOException e) {
        System.err.println("创建目录失败: " + e.getMessage());
    }
} else {
    System.out.println("目录已存在");
}

在上面的代码中,将"路径/目录名"替换为你想要判断和创建的目录路径。

首先,使用Paths.get()方法创建一个Path对象表示目录的路径。然后,使用Files.exists()方法判断目录是否存在。如果目录不存在,使用Files.createDirectory()方法创建目录,并输出"目录已创建"。如果创建目录失败,将捕获IOException并输出错误信息。如果目录已存在,将输出"目录已存在"。

请确保在运行代码时具有足够的权限来读取和写入指定的目录

java8 判断目录是否存在不存在就创建

原文地址: http://www.cveoy.top/t/topic/izuy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录