嵌套归档文件的有效Java.net.URIs是否存在?

7

虽然不太建议这样做,但是可以使用jar: URI方案读取基本上是重命名为.zip的文档格式(.ear, .war, .jar等)。

例如,当uri变量评估为单个顶级存档文件时,如uri等于jar:file:///Users/justingarrick/Desktop/test/my_war.war!/时,下面的代码可以很好地工作:

private FileSystem createZipFileSystem(Path path) throws IOException {
    URI uri = URI.create("jar:" + path.toUri().toString());
    FileSystem fs;

    try {
        fs = FileSystems.getFileSystem(uri);
    } catch (FileSystemNotFoundException e) {
        fs = FileSystems.newFileSystem(uri, new HashMap<>());
    }

    return fs;
}

然而,当URI包含嵌套归档文件时,例如当uri等于jar:jar:file:///Users/justingarrick/Desktop/test/my_war.war!/some_jar.jar! /(一个.war中的.jar)时,getFileSystem和newFileSystem调用将失败,并显示IllegalArgumentException。 是否存在用于嵌套存档文件的有效java.net.URI方案?

1
从记忆中来看,我的答案是否定的。Java仍然存在未修复的关于在URI中转义!的错误(尝试将那个感叹号添加到目录名称的末尾,然后将其添加到类路径中),因此我的直觉是说你需要做一些工作才能让它按照你想要的方式工作。 - ngreen
1
从Java源代码(java.net.JarURLConnection)来看,答案也是否定的: int separator = spec.indexOf("!/");
/*
* 提醒:我们不处理嵌套的JAR URL
*/
...
- Jonas Berlin
1个回答

1
正如 Jonas Berlin 在上面的评论中所述,答案是“不”。从 java.net.JarURLConnection source 中可以看出。
/* get the specs for a given url out of the cache, and compute and
 * cache them if they're not there.
 */
private void parseSpecs(URL url) throws MalformedURLException {
    String spec = url.getFile();

    int separator = spec.indexOf("!/");
    /*
     * REMIND: we don't handle nested JAR URLs
     */
    if (separator == -1) {
        throw new MalformedURLException("no !/ found in url spec:" + spec);
    }

    jarFileURL = new URL(spec.substring(0, separator++));
    entryName = null;

    /* if ! is the last letter of the innerURL, entryName is null */
    if (++separator != spec.length()) {
        entryName = spec.substring(separator, spec.length());
        entryName = ParseUtil.decode (entryName);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接