使用Java nio创建子目录和文件 [英] Using Java nio to create a subdirectory and file

查看:1140
本文介绍了使用Java nio创建子目录和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a simple program that will try to read in "conf/conf.xml" from disk, but if this file or dir doesn't exist will instead create them.

我可以使用以下代码执行此操作:

I can do this using the following code:

    // 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(); }
    }

我的问题是,这真的是最优雅的方式吗?在新的子目录中创建一个新文件只需要创建两个简单的路径就好了。

My questions is if this really the most elegant way to do this? It seems superflous to need to create two Paths simple to create a new file in a new subdirectory.

推荐答案

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

You could declare your confFile as File instead of Path. Then you can use confFile.getParentFile().mkdirs();, see example below:

// ...

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

// ...

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

Or, using your code as is, you can use:

Files.createDirectories(confFile.getParent());

这篇关于使用Java nio创建子目录和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆