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

我正在创建一个简单的程序,它将尝试从磁盘读取“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());