2016-02-10 21 views
0

我有一個路徑化子性質的文件到文件我的罐子裏加載文件給出了錯誤的道路

logo.cgp=images/cgp-logo.jpg 

這個文件已經存在:

enter image description here

我想加載這個文件在我的項目,所以我這樣做:

String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg" 
File file = new File(getClass().getClassLoader().getResource(property).getFile()); 

但後來當我做file.exists()我得到false。當我檢查file.getAbsolutePath()它導致C:\\images\\cgp-logo.jpg

我在做什麼錯?

回答

0

可以使用JarFile類是這樣的:

JarFile jar = new JarFile("foo.jar"); 
String file = "file.txt"; 
JarEntry entry = jar.getEntry(file); 
InputStream input = jar.getInputStream(entry); 
OutputStream output = new FileOutputStream(file); 
try { 
    byte[] buffer = new byte[input.available()]; 
    for (int i = 0; i != -1; i = input.read(buffer)) { 
     output.write(buffer, 0, i); 
    } 
} finally { 
    jar.close(); 
    input.close(); 
    output.close(); 
} 
2

好一個罐子內的文件只是一個普通的文件。它是一個可以由ClassLoader加載並作爲流而不是文件讀取的資源。

根據的Javadoc,getClass().getClassLoader().getResource(property)返回上一個URL的URLgetFile()說:

獲得此URL的文件名。返回的文件部分將與getPath()相同,再加上getQuery()的值的串聯(如果有的話)。如果沒有查詢部分,則此方法和getPath()將返回相同的結果。

所以對於一個罐子的資源是一樣的getPath()返回:

這個URL,或一個空字符串的路徑部分,如果不存在

所以在這裏您將返回/images/cgp-logo.jpg相對於類文件路徑,它不對應於文件系統上的真實文件。這也解釋了file.getAbsolutePath()

的正確方法的返回值來獲得對資源的訪問是:

InputStream istream = getClass().getClassLoader().getResourceAsStream(property)