我有两个 URI 对象。一个指向一个 JAR 文件中的文件夹,另一个指向同一个 JAR 文件中的一个文件。该文件位于第一个 URI 指定的目录的子文件夹中。我喜欢创建一个相对 URI,因此生成的 URI 仅包含 JAR 中文件的相对路径。
文件夹 URI
jar:file:/C:/Users/inagy/.m2/repository/hu/inagy/my-config-artifact/2.0-SNAPSHOT/my-config-artifact-2.0-SNAPSHOT.jar!/conf/
资源 URI
jar:file:/C:/Users/inagy/.m2/repository/hu/inagy/my-config-artifact/2.0-SNAPSHOT/my-config-artifact-2.0-SNAPSHOT.jar!/conf/somesubpath/someconfig.xml
调用
folderUri.relativize(resourceURI)
后,我期望得到以下 URI:somesubpath/someconfig.xml
但是我得到了 resourceURI,这意味着根据 URI class's Javadoc JDK 代码发现这两条路径彼此不相关。
这是一个错误还是我做错了什么?
最佳答案
我也被这件事弄得有些恼火。答案与 JAR 文件的语义无关 — 它与 jar:
URI 的语法有关。要“相对化”,URI 必须分层且不透明。您将从 java.net.URI 的 JavaDoc 中注意到:
At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
...
An opaque URI is an absolute URI whose scheme-specific part does not begin with a slash character ('/'). Opaque URIs are not subject to further parsing.
...
A hierarchical URI is subject to further parsing according to the syntax
[scheme:][//authority][path][?query][#fragment]
像 jar:file:///home/me/foo.jar!/conf/
这样的 JAR URI 被解析为:
- 方案 =
jar
- scheme-specific-part =
file:///home/me/foo.jar!/conf/
- 片段=(无)
因为 scheme-specific-part 不以“/
”开头,所以不能将其视为分层 URI。 URI 类不会特殊处理 jar:
(或任何)URI,因此它无法识别 file://
部分是一个嵌套的 URI,是 分层。
由于 jar:
URI 是不透明的且没有层次结构,因此它们受制于为 URI#relativize() 记录的行为:
The relativization of the given URI against this URI is computed as follows:
- If either this URI or the given URI are opaque, [...], then the given URI is returned.
编辑:遗漏了关于不透明 URI 的关键部分。
关于java.net.URI.relativize 不适用于 JAR URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13046150/