[英]Trying to read a resource file from within a jar
我已經閱讀了有關此主題的每個問題和答案,並且嘗試了許多建議的解決方案,但都沒有用,目前我正在嘗試使用URL資源方法,但url始終返回null。 這是我當前的偽設置:
/src/java/pkg/name/is/long/meatpackage/MyClassFile.java
/src/java/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt
@SuppressWarnings("rawtypes")
Class thisClass = Class.forName("pkg.name.is.long.meatpackage.MyClassFile");
ClassLoader cLoader = thisClass.getClassLoader();
//note, I have tried a plethora of variations to the path for the file, this is just one example
URL url = cLoader.getResource("pkg/name/is/long/meatpackage/myresources/myresourcefile.txt");
System.out.println("Found the file!!: " + url);
認真地說,在您的jar中包含一個文本文件並在運行時訪問它不是很難嗎?
當我列出jar時,它表明文件位於pkg / name / is / log / meatpackage / myresources / myresourcefile.txt中。
我嘗試過的另一種方法是:
//along with multiple path combinations for the file the InputStream is always null.
//multiple paths include but are not limited to:
// "pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/myresources/myresourcefile.txt"
// "/myresourcefile.txt"
// "myresourcefile.txt"
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("myresourcefile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
您可以使用getClass()。getResourceAsStream()或MyClassFile.getResourceAsStream()簡化此過程-無需直接與類加載器對話。
請注意,資源名稱以斜杠分隔,如果您指定/,則它是從JAR的根目錄或類路徑的基部開始的,否則它與類是相同的包目錄中的隱含目錄。
例如:
包com.example; 公共類Foo {靜態{Foo.class.getResourceAsStream(“ bar.txt”); //尋找/com/example/bar.txt Foo.class.getResourceAsStream(“ / bar.txt”); //尋找/bar.txt}}
如果您在Eclipse中進行開發,請注意, getResourceAsStream
僅在編譯后的輸出目錄中查找(即bin
任何內容)。 因此,如果您的資源不在此處,請將其復制到src
目錄中(以便在構建時將其復制到bin
目錄中),並且應該可以正確找到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.