使用JavaNIO创建子目录和文件
我正在创建一个简单的程序,它将尝试从磁盘读取“conf/conf.xml”,但如果这个文件或目录不存在,它将创建它们 我可以使用以下代码执行此操作:使用JavaNIO创建子目录和文件,java,file,nio,Java,File,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
// 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
声明为文件,而不是路径
。然后可以使用confFile.getParentFile().mkdirs()代码>,请参见下面的示例:
// ...
File confFile = new File("./conf/conf.xml");
confFile.getParentFile().mkdirs();
// ...
或者,按原样使用代码,您可以使用:
Files.createDirectories(confFile.getParent());
您可以执行以下操作:
// Get your Path from the string
Path confFile = Paths.get("./conf/conf.xml");
// Get the portion of path that represtents directory structure.
Path subpath = confFile.subpath(0, confFile.getNameCount() - 1);
// Create all directories recursively
/**
* Creates a directory by creating all nonexistent parent directories first.
* Unlike the {@link #createDirectory createDirectory} method, an exception
* is not thrown if the directory could not be created because it already
* exists.
*
*/
Files.createDirectories(subpath.toAbsolutePath()))
您可以在一个代码行中创建目录和文件:
Files.createFile(Files.createDirectories(confDir).resolve(confFile.getFileName())
Files.createDirectories(confDir)
如果文件夹已经存在并且在任何情况下都返回路径,则不会引发异常。Path
具有.resolve()
和.getParent()
,因此,您可以从这里开始我不明白您的异常逻辑:如果目录不存在且无法创建,为什么要尝试创建该文件?如果.conf/已经存在,使用mkdirs()或createDirectories(..)不会引发异常吗?我可以看到如何使用该文件,但我想知道为什么nio下的路径/文件没有一种同样简单的方法来实现这一点。@user3341332否。它根本不会抛出异常。请参阅Javadoc。但是请注意,如果路径的“字符串”中没有其他部分,则Path.getParent()
返回null
。例如,带有dir/b.txt的Path
将返回Pathdir
,但dir.getParent()
将返回null
。所以Files.createDirectories(dir.getParent())
抛出一个NullPointerException
,尽管dir
在其他目录中。当您开始使用java.nio.Path时,为什么要返回java.io.File?代码的简要描述,键函数或者,当用户尝试或从现有答案中选择解决方案时,它的不同之处会很有用。虽然此代码可能会解决问题,但它如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。代码对java开发人员来说是不言而喻的)我添加了一些解释文件。如果目录已经存在,CreateDirectory(confDir)
将抛出FileReadyExistsException
。@mks-d我已验证-运行代码2次,不会出现异常。您使用哪个java版本?