嵌套文件的有效java.net.URI是否存在?

2019年4月11日 46点热度 0条评论

通过使用jar: URI scheme,有可能(尽管建议不当)读取基本上已重命名为.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包含嵌套文件(例如,当
getFileSystem等于
newFileSystem(.war内部的.jar)时。

嵌套存档文件是否有有效的
IllegalArgumentException方案?

解决方案如下:

如上述乔纳斯·柏林(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);
    }
}