2014-11-14 25 views
6

這是可能的,但也許是不明智的,讀取存檔格式,基本上改名的.zip文件的.ear的.war的.jar等),通過使用jar:URI scheme是否存在嵌套存檔的有效java.net.URI?

例如,當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; 
} 

然而,getFileSystemnewFileSystem呼叫失敗,並IllegalArgumentException當URI包含嵌套存檔,例如當uri等於jar:jar:file:///Users/justingarrick/Desktop/test/my_war.war!/some_jar.jar!/(a .jar內部的.war)。

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

+1

從記憶中,我會說答案是否定的。 Java在URI中轉義'!'仍然存在未定義的錯誤(嘗試在目錄名稱的末尾添加一個bang,然後將其添加到你的類路徑中),所以我的直覺反應是說你會有一些工作要做讓它按照你想要的方式工作。 – ngreen 2014-11-30 22:20:16

+1

從java源代碼(java.net.JarURLConnection),答案也是no: 'int separator = spec.indexOf(「!/」); /* *注意:我們不處理嵌套的JAR URL */ ...' – 2014-12-11 12:17:26

回答

0

正如喬納斯柏林在上面的評論中所述,答案是。從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); 
    } 
} 
相關問題