4 回答

TA貢獻1836條經驗 獲得超13個贊
而不是嘗試將資源作為文件來處理,而只是要求ClassLoader通過getResourceAsStream返回資源的InputStream:
InputStream in = getClass().getResourceAsStream("/file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
只要file.txt
資源在類路徑上可用,那么無論file.txt
資源是在classes/
目錄中還是在內部,這種方法都將以相同的方式工作jar
。
之所以URI is not hierarchical
發生這種情況,是因為jar文件中資源的URI看起來像這樣:file:/example.jar!/file.txt
。您無法讀取jar
(zip
文件)中的條目,就像它是一個普通的舊文件。
這可以通過以下答案得到很好的解釋:

TA貢獻1900條經驗 獲得超5個贊
要訪問jar中的文件,您有兩個選擇:
將文件放在與包名匹配的目錄結構中(在解壓縮.jar文件后,它應該與.class文件位于同一目錄中),然后使用
getClass().getResourceAsStream("file.txt")
將文件放在根目錄下(在解壓縮.jar文件后,它應該在根目錄中),然后使用它來訪問它
Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt")
當jar用作插件時,第一個選項可能不起作用。

TA貢獻1773條經驗 獲得超3個贊
如果你想讀作文件,我相信仍有類似的解決方案:
ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("file/test.xml").getFile());

TA貢獻1808條經驗 獲得超4個贊
之前我遇到過這個問題,我做了后備加載方式?;旧系谝环N方式在.jar文件中工作,第二種方式在eclipse或其他IDE中工作。
public class MyClass { public static InputStream accessFile() { String resource = "my-file-located-in-resources.txt"; // this is the path within the jar file InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource); if (input == null) { // this is how we load file within editor (eg eclipse) input = MyClass.class.getClassLoader().getResourceAsStream(resource); } return input; }}
添加回答
舉報