2012-05-04 92 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