【问题标题】:Creating a path between two paths in Java using the Path class使用 Path 类在 Java 中的两个路径之间创建路径
【发布时间】:2013-04-24 08:33:08
【问题描述】:

thisoracle java教程中的这句话是什么意思:

如果只有其中一个路径,则无法构造相对路径 包括一个根元素。如果两个路径都包含一个根元素,则 构建相对路径的能力取决于系统。

“系统依赖”是否仅仅意味着如果一个元素包含一个根,它只能在已编写的平台特定语法中工作? 我想这是他们唯一的意思。 还有其他的阅读方式吗?

例如:

public class AnotherOnePathTheDust {
    public static void main (String []args)
    {
    Path p1 = Paths.get("home");
    Path p3 = Paths.get("home/sally/bar"); //with "/home/sally/bar" i would get an exception.
    // Result is sally/bar
    Path p1_to_p3 = p1.relativize(p3);
    // Result is ../..

    Path p3_to_p1 = p3.relativize(p1);
    System.out.println(p3_to_p1);   }
}

我使用“/home/sally/bar”而不是“home/sally/bar”(没有root)得到的例外是这个:

 java.lang.IllegalArgumentException: 'other' is different type of Path

为什么它不起作用?与系统的冲突是什么意思?

【问题讨论】:

    标签: java path relative-path


    【解决方案1】:

    因为p1p3 的根不同。

    如果您对p3 使用“/home/sally/bar”而不是“home/sally/bar”,则p3.getRoot() 将返回/,但p1.getRoot() 为空。

    阅读以下代码(来自http://cr.openjdk.java.net/~alanb/6863864/webrev.00/src/windows/classes/sun/nio/fs/WindowsPath.java-.html Line374-375)后,您就会知道为什么会出现此异常:

    // can only relativize paths of the same type
    if (this.type != other.type)
         throw new IllegalArgumentException("'other' is different type of Path");
    

    【讨论】:

      【解决方案2】:

      我对你的例子做了一些测试。实际上,您提到的异常仅在其中一个路径包含 root 而另一个不包含时出现(就像句子所说的那样)例如:

      • /home/sally/bar
      • 首页

      如果两个路径都包含根,则可以正常工作。 “系统依赖”可能意味着 Windows 上的这种情况:

      • C:\home
      • D:\home\sally\bar

      上面给出了以下异常:

      java.lang.IllegalArgumentException: 'other' has different root
      

      在 Unix 上你永远不会遇到这样的事情(两个路径都包含根路径 - 绝对路径除外)

      【讨论】:

      • 作为记录,我在 Ubuntu Linux 中收到了这个问题。不过,我确实认为这与第一部分有关 - 一个是绝对的,一个不是。
      • @Brad Lee - 你的意思是你的两个路径都包含 root 的异常?
      • 我刚刚发现,如果一个路径包含“file:/home”和其他“/home”,我在 Linux 上尝试对两者进行相对化时会遇到同样的错误
      【解决方案3】:

      正如已经提到的其他答案,这是由于路径中的不同根。

      要解决这个问题,您可以使用toAbsolutePath()

      例如:

      public class AnotherOnePathTheDust {
        public static void main (String []args)
        {
          Path p1 = Paths.get("home").toAbsolutePath();
          Path p3 = Paths.get("/home/sally/bar").toAbsolutePath();
      
          Path p1_to_p3 = p1.relativize(p3);
      
          Path p3_to_p1 = p3.relativize(p1);
          System.out.println(p3_to_p1);
        }
      }
      

      【讨论】:

        【解决方案4】:

        这里的系统依赖是指我假设的特定操作系统实现。因此,Linux 会以不同于 Windows 的方式处理这个问题,等等。如果没有根路径(即以 / 开头的路径),则假定两条路径是同级的,位于同一级别(即在 /home/sally 中)。因此,当您尝试相对化时,如果它们不在同一级别上,则无法保证非根路径的存储位置,如果您考虑一下,这是有道理的。这有帮助吗?

        【讨论】:

          猜你喜欢
          • 2011-08-08
          • 2017-03-29
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          • 2019-03-12
          • 1970-01-01
          • 2017-08-10
          • 1970-01-01
          相关资源
          最近更新 更多