
以下是如何使用files.exists方法来检查目录是否存在,并仅在目录不存在时才创建它的示例代码:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDirectoryIfNotExists {
public static void main(String[] args) {
String directoryPathString = "C:\csv\nov"; // 替换为你的目录路径
Path directoryPath = Paths.get(directoryPathString);
String subDirectoryName = "processed";
try {
Path path = Paths.get(directoryPath.toAbsolutePath() + "/" + subDirectoryName);
// 检查目录是否存在
if (!Files.exists(path)) {
// 如果目录不存在,则创建它
Files.createDirectory(path);
System.out.println("目录创建成功: " + path);
} else {
System.out.println("目录已存在: " + path);
}
} catch (IOException e) {
System.err.println("创建目录失败: " + e.getMessage());
e.printStackTrace(); // 打印完整的堆栈信息,便于调试
}
}
}代码解释:
注意事项:
总结:
通过使用 Files.exists() 方法预先检查目录是否存在,可以有效地避免 FileAlreadyExistsException 异常,使程序更加健壮。 同时,良好的异常处理能够帮助我们更好地理解和解决潜在的问题。 在实际开发中,请根据具体需求调整代码,并注意处理可能出现的异常。
以上就是输出格式要求:创建目录时跳过已存在的目录的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号