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

时间:2014-02-22 17:54:32

标签: 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 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(); }
    }

我的问题是,这真的是最优雅的方式吗?在新的子目录中创建一个新文件非常简单,需要创建两个Paths。

3 个答案:

答案 0 :(得分:17)

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

// ...

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

// ...

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

Files.createDirectories(confFile.getParent());

答案 1 :(得分:1)

您可以在一个代码行中创建目录和文件:

Files.createFile(Files.createDirectories(confDir).resolve(confFile.getFileName()))

Files.createDirectories(confDir)将不会抛出异常,如果该文件夹已经存在并在任何情况下都返回Path。

答案 2 :(得分:0)

您可以执行以下操作:

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