java - 解析 java.nio.files.Path 时忽略前导斜杠的最佳方法是什么

标签 java nio filepath

我正在尝试使用 java.io.File 重构一些遗留代码,以使用 java.nio.file.Path 代替。

我对 Path 对绝对文件路径有更好的支持这一事实感到震惊,因为我收到的许多值都有一个前导斜杠 (/),而它们应该表示相对路径。这样字符串连接更容易,但我试图摆脱 String/File 来表示文件路径。

旧的行为是 new File(parent, child) 返回一个新的 File 表示

  • 父目录下的子文件/目录,无论子文件/目录是否以 / 开头。

新的行为是 parent.resolve(child) 返回一个新的 Path 代表任一

  • 父目录下的子文件/目录
  • child 作为根(如果它以 / 开头)

我认为新方法可以使代码更简洁,但是在重构遗留应用程序时,它可能会引入微妙的错误。

使用Path时恢复旧的(文件)行为的最佳/最干净的方法是什么?

<小时/>
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

class Main {
  public static void main(String[] args) {
    file();
    path();
  }

  public static void file(){
    File root = new File("/root");
    File relative = new File(root, "relative");
    File absolute = new File(root, "/absolute");

    System.out.println("File:");
    System.out.println(relative.getAbsolutePath()); // prints "/root/relative"
    System.out.println(absolute.getAbsolutePath()); // prints "/root/absolute"
    System.out.println();
  }

  public static void path(){
    Path root = Paths.get("/root");
    Path relative = root.resolve("relative");
    Path absolute = root.resolve("/absolute");

    System.out.println("Path:");
    System.out.println(relative.toAbsolutePath()); // prints "/root/relative"
    System.out.println(absolute.toAbsolutePath()); // prints "/absolute" but should print "/root/absolute"
    System.out.println();
  }
}
<小时/>

基本上,我想要的是一种采用父路径和子字符串的方法,该方法返回父+子路径,无论子路径是否有前导 /
像这样的东西,但没有依赖于我知道配置将使用 / (而不是 \)的字符串操作:

private static Path resolveSafely(Path parent, String child) {
    child = child.startsWith("/")
            ? child.substring(1)
            : child;
    parent.resolve(child);
}

最佳答案

我能找到的最好方法是:

    Path root = Paths.get("/root");
    Path relative = root.resolve("relative");
    Path absolute = Paths.get(root.toString(), "/absolute");

    System.out.println("Path:");
    System.out.println(relative.toAbsolutePath()); // prints "/root/relative"
    System.out.println(absolute.toAbsolutePath()); // prints "/root/absolute"
    System.out.println();

希望这就是您所需要的。

编辑:自 Java 11 起,Path.of() 可用,并且是获取 Path 对象的推荐方法,而不是 Paths.get()Check javadoc其中还指出 Paths 类可能在未来版本中被弃用。

关于java - 解析 java.nio.files.Path 时忽略前导斜杠的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60565892/

相关文章:

Java MINA 暴露套接字

PHP 目录的经验法则?

java - 如何从资源中引用xml文件? eclipse

java - 滞后套接字java

java - 如何从另一个类执行一个类的方法?

java - 如何将此代码放入可调用方法类中

c# - 如何获取项目之间共享的app.settings文件的相对文件路径

java - 配置本地 Nexus 服务器以从其他远程 Nexus 存储库下载 Artifact

java - 使用网络应用程序上传大文件

java - 覆盖通过 FileDescriptor FD 获取的 FileOutputStream 中的属性文件