2013-02-27 136 views
0

我知道我的問題似乎已經回答過,但我無法找到我的案例的答案。如何從資源中獲取文件

我在做什麼,是從資源中獲取文件類型,所以當它打包時,它可以被訪問。我找到的答案是試圖讀取該文件,但我真正需要的是構建一個File對象,因爲我有一個期待該對象的第三方庫。

這裏是我試過的代碼:

String xslFilePath = new Test().getClass().getResource("/com/test/decision_template.xsl").getPath(); 
    System.out.println(xslFilePath); 
    File xsltfile = new File(xslFilePath); 
    System.out.println(xsltfile.getAbsolutePath()+", exist:"+xsltfile.exists()); 

我得到了這樣的結果:

C:\>java -jar test.jar 
    file:/C:/test.jar!/com/test/decision_template.xsl 
    C:\\file:\C:\test.jar!\com\test\decision_template.xsl, exist:false 
    java.io.FileNotFoundException: file:\C:\test.jar!\com\test\decision_template.xsl 
    (Syntaxe du nom de fichier, de rÚpertoire ou de volume incorrecte) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:120) 
    at com.test.Test.main(Test.java:30) 

我需要一種方法來獲取文件,因此在.exists()返回true。

+2

這個問題已經有很多答案給你:http://stackoverflow.com/questions/403256/how-do-i-read-a-resource-file-from-a-java-jar-file。最合理的做法是不需要文件,但通常只需要一個'InputStream'。 – 2013-02-27 19:09:55

回答

0

您可以嘗試TrueZip庫。這是相當不錯。我相信你需要實現你自己的DirectoryScanner或其他東西。

更好的是,只需敲一下自己的實現,即可掃描類路徑中的所有jar。 Here's an example我在GitHub上的一個項目中完成了它。我認爲你可以輕鬆地定製它來滿足你的需求。

玩得開心! :)