2012-05-04 107 views
6

可能重複:
Java resource as file包括JAR文件中的文本文件和讀取它

我是一種新的Java和我試圖讓裏面的文本文件Jar文件。

當我執行我的jar時,我必須將我的文本文件放在與jar fil相同的文件夾中。如果文本文件不在那裏,我會得到一個NullPointerException,這是我想避免的。

我想要做的是獲取罐子裏面的txt文件,所以我不會有這個問題。我試了一些指南,但他們似乎沒有工作。我目前的閱讀功能是這樣的:

public static HashSet<String> readDictionary() 
{ 
    HashSet<String> toRet = new HashSet<>(); 
    try 
    { 
      // Open the file that is the first 
      // command line parameter 
      FileInputStream fstream = new FileInputStream("Dictionary.txt"); 
     try (DataInputStream in = new DataInputStream(fstream)) { 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String strLine; 
      //Read File Line By Line 
      while ((strLine = br.readLine()) != null) { 
      // Read Lines 
       toRet.add(strLine); 
      } 
     } 
      return toRet; 
    } 
    catch (Exception e) 
    {//Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
    } 
    return null; 
} 

回答

7

不要試圖在Jar文件中找到文件作爲「文件」。改用資源。

獲得對類或類加載器的引用,然後在類或類加載器調用getResourceAsStream(/* resource address */);

你也應該在你的搜索技巧上工作,因爲這已經被無數次地問及和回答了。事實上,我們可能應該關閉這個問題,因爲我不認爲它增加了已經存在於SO上的討論。

2

好像這個問題的精確副本:How do I access a config file inside the jar?您的問題

進一步NullPointerException,我建議不要以確保它不會發生,而是爲它準備並妥善處理。我會更進一步請你總是檢查你的變量爲空值,這是一件好事。

3
// add a leading slash to indicate 'search from the root of the class-path' 
URL urlToDictionary = this.getClass().getResource("/" + "Dictionary.txt"); 
InputStream stream = urlToDictionary.openStream(); 

另請參閱this answer