在jar文件中包含一个文本文件并将其读取

可能重复:
Java资源作为文件

我是Java的新手,我试图在Jar文件中获取一个文本文件。

在我执行我的jar时,我必须将我的文本文件放在与jar文件相同的文件夹中。 如果文本文件不存在,我将得到一个NullPointerException ,我想避免。

我想要做的是在jar中获取txt文件,所以我不会遇到这个问题。 我尝试了一些指南,但它们似乎没有用。 我目前的读取function如下:

 public static HashSet readDictionary() { HashSet 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; } 

不要试图在Jar文件中找到文件作为“文件”。 请改用资源。

获取对类或类加载器的引用,然后在类或类加载器上调用getResourceAsStream(/* resource address */);

你也应该研究你的搜索技巧,因为这里已经被无数次地询问和回答了。 事实上,我们应该关闭这个问题,因为我没有看到它增加了已经出现在SO上的讨论。

 // 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(); 

另见这个答案 。

看起来像这个问题的完全相同: 如何访问jar中的配置文件?

除了NullPointerException的问题之外,我建议不要确保它不会发生,而是为它准备并正确处理它。 我会进一步要求你总是检查你的变量的空值,这是一件好事。