我已閱讀關於此主題的每一個問題和答案,並且我嘗試了許多建議的解決方案,其中沒有一個正在工作,目前我正在嘗試使用URL資源方法,但url總是返回null。這是我目前的僞設置:試圖從罐子裏讀取資源文件
/src/java/pkg/name/is/long/meatpackage/MyClassFile.java
/src目錄/ JAVA /包裝/名/是/長/ 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));
那麼,被調用的方法是否需要靜態?我在發佈之前就已經嘗試過了,因爲它是類似問題的建議之一,但只是爲了確保幾分鐘前我再次嘗試過。 getResourceAsStream的兩種方法都不返回非null的InputStream。同樣,當我列出jar文件的內容時,我已經嘗試將該文件放在您可以想到的每個位置。雖然它真的只適合將它放在與類相同的包中的資源目錄中,但我試圖將它移動到目錄結構中無效。 – JoGotta
靜態沒有區別..我將方法更改爲靜態並使用MyClassFile.class.getResourceAsStream無濟於事。我準備放棄.. – JoGotta
不,它不需要是靜態的。驗證您的文件是否位於編譯的輸出目錄中,並確保文件引用以/開頭,如果您想放入完全限定的軟件包。 – AlBlue