使用 Path 类在 Java 中的两个路径之间创建路径 [英] Creating a path between two paths in Java using the Path class

查看:49
本文介绍了使用 Path 类在 Java 中的两个路径之间创建路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this中的这句话到底是什么意思oracle java教程:

What does exactly mean this sentence from this oracle java tutorial:

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

A relative path cannot be constructed if only one of the paths includes a root element. If both paths include a root element, the capability to construct a relative path is system dependent.

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

With "system dipendent" do they mean only that if an element contains a root it will work only in the platform specific syntax that has been written? I guess it is the only thing they mean. Are there any other ways of reading that?

例如:

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)得到的例外是这个:

The exception that I get by using "/home/sally/bar" instead of "home/sally/bar" (without root) is this one:

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

为什么不起作用?他们所说的与系统的冲突是什么?

Why does it not work? what is the conflict with the system that they mean?

推荐答案

因为 p1p3 的根不同.

Because p1 and p3 has different root.

如果您使用/home/sally/bar"而不是home/sally/bar"作为p3,那么p3.getRoot() 将返回/p1.getRoot() 为空.

If you use use "/home/sally/bar" instead of "home/sally/bar" for p3, then p3.getRoot() will return / but p1.getRoot() is null.

阅读以下代码(来自http://cr.openjdk.java.net/~alanb/6863864/webrev.00/src/windows/classes/sun/nio/fs/WindowsPath.java-.html Line374-375):

You'll know why you got this exception after you read following codes (comes from 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");

这篇关于使用 Path 类在 Java 中的两个路径之间创建路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆