【问题标题】:Getting an element inside a directory using java.nio.file.Path's使用 java.nio.file.Path 获取目录中的元素
【发布时间】:2020-06-16 15:34:19
【问题描述】:

我目前正在掌握 Java 中的文件管理。据我所知,java.nio.file.Path 是这样做的首选方式。

假设我想将 oldDir 的内容复制到当前为空的 newDir。每次复制文件时,我都需要这条长线来获取 newFile 的路径:

Path newDir = FileSystems.getDefault().getPath("new");
Path oldDir = FileSystems.getDefault().getPath("old");
for (Path oldFile : oldDir) {
    Path newFile = FileSystems.getDefault().getPath("new", oldFile.getFileName().toString()); // Why so complicated? :(
    Files.copy(oldFile, newFile);
}

有没有像newDir.getChild(oldFile.getFileName()) 这样的东西来做我想做的事,或者真的没有更短的方法吗?

【问题讨论】:

  • newDir.resolve(oldFile.getFileName())

标签: java file io java.nio.file


【解决方案1】:

您可以做一些事情来简化代码:

  1. 使用Path#of(String,String...) 或Paths#get(String,String...) 创建您的Path 实例。这两种方法都委托给默认的FileSystem。前者是在 Java 11 中添加的,现在是首选方法。

  2. 使用Path#resolve(Path) 将相对路径附加到某个绝对路径。

但是您的代码中也存在错误。您正在迭代 oldDir,因为 Path 实现了 Iterable<Path>。 然而,它迭代路径的名称,而不是路径的子节点。换句话说,这是:

Path path = Path.of("foo", "bar", "file.txt");
for (Path name : path) {
  System.out.println(name);
}

将输出:

foo
bar
file.txt

如果你想遍历一个目录的子目录,你需要使用Files#list(Path) 或Files#newDirectoryStream(Path) 之类的东西(后者有两个重载)。这两种方法都只返回目录的直接子级。还有其他方法可用于递归迭代目录及其子目录;浏览 Files 文档以查看提供的内容。

所以你的代码应该看起来像这样:

Path oldDir = Path.of(...);
Path newDir = Path.of(...);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(oldDir)) {
  for (Path oldFile : dirStream) {
    Path newFile = newDir.resolve(oldFile.getFileName());
    Files.copy(oldFile, newFile);
  }
}

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2022-01-20
    • 2021-05-26
    相关资源
    最近更新 更多