【问题标题】:Including a text file inside a jar file and reading it [duplicate]在jar文件中包含一个文本文件并读取它[重复]
【发布时间】:2012-05-14 05:36:55
【问题描述】:

可能重复:
Java resource as file

我是 Java 新手,我正在尝试在 Jar 文件中获取文本文件。

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

我想要做的是将 txt 文件放入 jar 中,这样我就不会遇到这个问题了。我尝试了一些指南,但它们似乎没有用。我当前的读取功能是这样的:

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;
}

【问题讨论】:

    标签: java jar nullpointerexception embedded-resource


    【解决方案1】:

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

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


    请参阅下面的类似问题(如果可能,请避免创建新问题):

    【讨论】:

      【解决方案2】:
      // 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

      【讨论】:

        【解决方案3】:

        似乎与此问题完全相同:How do I access a config file inside the jar?

        关于NullPointerException 的问题,我建议不要确保它不会发生,而是要做好准备并妥善处理。我会进一步要求您始终检查您的变量是否为空值,这是一件好事。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-04
          • 1970-01-01
          • 2012-10-09
          • 2023-04-04
          • 2018-04-10
          • 1970-01-01
          • 1970-01-01
          • 2012-10-29
          相关资源
          最近更新 更多