【问题标题】:Using Java nio to create a subdirectory and file使用Java nio创建子目录和文件
【发布时间】:2014-03-24 08:43:51
【问题描述】:

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

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

【问题讨论】:

  • Path.resolve().getParent(),所以你可以从那里开始
  • 我没看懂你的异常逻辑:为什么目录不存在且无法创建,为什么还要尝试创建文件?

标签: java file nio


【解决方案1】:

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

// ...

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

// ...

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

Files.createDirectories(confFile.getParent());

【讨论】:

  • 如果 .conf/ 已经存在,不会使用 mkdirs() 或 createDirectories(..) 触发异常?我可以看到如何使用 File 来完成,但想知道为什么路径/文件下nio 没有同样简单的方法来做到这一点。
  • @user3341332 不。它根本不会抛出异常。请参阅 Javadoc。
  • 但请注意,如果路径的“字符串”中没有更多部分,Path.getParent() 将返回 null。例如,带有dir/b.txtPath 将返回路径dir,但dir.getParent() 将返回null。所以Files.createDirectories(dir.getParent()); 抛出一个NullPointerException 尽管dir 在其他目录中。
  • 从 java.nio.Path 开始的时候为什么要回到 java.io.File?
【解决方案2】:

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

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

如果文件夹已经存在,Files.createDirectories(confDir) 不会抛出异常,无论如何都会返回 Path。

【讨论】:

  • 在用户尝试或从现有答案中选择解决方案时,简要说明代码、关键功能或不同之处会很有用。
  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
  • 代码为java开发者说话)我添加了一些解释
  • 如果目录已经存在,Files.createDirectories(confDir) 将抛出 FileAlreadyExistsException
  • @mks-d 我验证了 - 运行代码 2 次并且没有出现异常。您使用哪个 java 版本?
【解决方案3】:

您可以执行以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多