Java URI 本地文件系统解析问题

Java URI local file system resolve issue

我有两个 URI,我想从第二个 URI 连接文件,如下所示: ...

  URI uri1 = new URI("file:/C:/Users/TestUser/Desktop/Example_File/");
  URI uri2 = new URI("/Example_File.xlsx");

after uri1.resolve(uri2) I want to get -> file:/C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx

... 上面的 resolve uri returns file:/Exampe_File.xlsx 这不是我预期的结果。如何连接这两个 URI?

要解决,第二个URI不应该有前导/

URI uri1 = new URI("C:/Users/TestUser/Desktop/Example_File/");
URI uri2 = new URI("Example_File.xlsx");
System.out.println(uri1.resolve(uri2)); 
// C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx

来自URI#resolve(URI)的文档:

[...]

Otherwise this method constructs a new hierarchical URI in a manner consistent with RFC 2396, section 5.2; that is:

  1. A new URI is constructed with this URI's scheme and the given URI's query and fragment components.
  2. If the given URI has an authority component then the new URI's authority and path are taken from the given URI.
  3. Otherwise the new URI's authority component is copied from this URI, and its path is computed as follows:
    1. If the given URI's path is absolute then the new URI's path is taken from the given URI. [emphasis added]
    2. Otherwise the given URI's path is relative, and so the new URI's path is computed by resolving the path of the given URI against the path of this URI. This is done by concatenating all but the last segment of this URI's path, if any, with the given URI's path and then normalizing the result as if by invoking the normalize method.

URI 的 class 文档指出:

The path component of a hierarchical URI is itself said to be absolute if it begins with a slash character ('/') [emphasis added]; otherwise it is relative. The path of a hierarchical URI that is either absolute or specifies an authority is always absolute.

因为你有 URI uri2 = new URI("/Example_File.xlsx") 你正在解析一个带有 绝对路径 的 URI 到另一个 URI。这意味着,根据文档,生成的 URI 路径将是 uri2 的路径。要解决此问题,请将 uri2 的路径设为相对路径。例如:

URI uri1 = new URI("file:/C:/Users/TestUser/Desktop/Example_File/");
URI uri2 = new URI("Example_File.xlsx"); // notice no leading slash

System.out.println(uri1.resolve(uri2));

输出:

file:/C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx