gpt4 book ai didi

java - 使用Java nio创建子目录和文件

转载 作者:太空狗 更新时间:2023-10-29 22:40:28 27 4
gpt4 key购买 nike

我正在创建一个简单的程序,它将尝试从磁盘读取“conf/conf.xml”,但如果此文件或目录不存在,则会创建它们。

我可以使用下面的代码来做到这一点:

    // create subdirectory path
Path confDir = Paths.get("./conf");

// create file-in-subdirectory path
Path confFile = Paths.get("./conf/conf.xml");

// if the sub-directory doesn't exist then create it
if (Files.notExists(confDir)) {
try { Files.createDirectory(confDir); }
catch (Exception e ) { e.printStackTrace(); }
}

// if the file doesn't exist then create it
if (Files.notExists(confFile)) {
try { Files.createFile(confFile); }
catch (Exception e ) { e.printStackTrace(); }
}

我的问题是这是否真的是最优雅的方式?需要创建两个简单的路径以在新子目录中创建新文件似乎是多余的。

最佳答案

您可以将 confFile 声明为 File 而不是 Path。然后你可以使用 confFile.getParentFile().mkdirs();,见下面的例子:

// ...

File confFile = new File("./conf/conf.xml");
confFile.getParentFile().mkdirs();

// ...

或者,按原样使用您的代码,您可以使用:

Files.createDirectories(confFile.getParent());

关于java - 使用Java nio创建子目录和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com