【问题标题】:Ensuring a text file is included in a JAR确保文本文件包含在 JAR 中
【发布时间】:2023-04-04 11:19:01
【问题描述】:

如果这是重复的,我深表歉意,我一直在四处寻找,但没有找到任何有用的东西。

我一直在尝试将项目导出为 JAR 文件,其中包括从文本文件中读取信息。在做了一些research 之后,我使用CLASSNAME.class.getClassLoader().getResourceAsStream("textFile.txt") 将阅读器从FileReader 更改为InputStreamReader。 (我也知道它应该在不涉及 getClassLoader() 方法的情况下工作)但是,getResourceAsStream("textFile.txt") 返回 null,当我尝试使用 BufferedReader 读取它时抛出 NullPointerException。

根据我的阅读,这是因为我的文本文件实际上不在 JAR 中。然而,当我 attempt to do 所以我仍然得到 NullPointerException。我也尝试将包含文件的文件夹添加到构建路径,但 that doesn't work either。我不确定如何检查文件是否真的在 JAR 中,如果没有,如何将它们放入 JAR 中以便可以找到并正确读取它们。

作为参考,我目前在 MacBook Air 上使用 Eclipse Neon,这是我尝试读取文本文件但失败的代码:

public static void addStates(String fileName) {
        list.clear();
        try {
            InputStream in = RepAppor.class.getClassLoader().getResourceAsStream("Populations/" + fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            /*
             * NOTE: A Leading slash indicates the absolute root of the directory, which is on my system
             * Don't use a leading slash if the root is relative to the directory
             */
            String line;
            while(!((line = reader.readLine()) == null)) {
                list.add(line);
        }
        reader.close();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "The file, " + fileName + ", could not be read.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (NullPointerException n) {
        JOptionPane.showMessageDialog(null, "Could not find " + fileName + ".\nNull Pointer Exception thrown", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

感谢您的考虑,感谢并欢迎您提出任何反馈意见。

【问题讨论】:

    标签: java jar


    【解决方案1】:

    有多种方法可以检查 .jar 文件的内容。

    大多数 IDE 都有一个“文件”部分,您可以在其中简单地展开 .jar 文件,就像它是一个目录一样。

    如果你的执行路径中有JDK的bin子目录,你可以在终端中使用jar命令:

    jar tf /Users/AaronMoriak/repappor.jar
    

    每个 .jar 文件实际上都是一个具有不同扩展名的 zip 文件(以及一个或多个 Java 特定的特殊条目)。因此,任何处理 zip 文件的命令都适用于 .jar 文件。

    由于您使用的是 Mac,因此您可以访问 Unix unzip 命令。在终端中,您可以简单地执行以下操作:

    unzip -v /Users/AaronMoriak/repappor.jar
    

    -v 选项的意思是“查看但不提取”)

    如果你的.jar文件有很多条目,可以限制上面命令的输出:

    unzip -v /Users/AaronMoriak/repappor.jar | grep Populations
    

    您关于前导斜杠的代码注释不太正确。但是,如果您删除 getClassLoader() 部分,则注释会更正确:

    // Change:
    // RepAppor.class.getClassLoader().getResourceAsStream
    // to just:
    // RepAppor.class.getResourceAsStream
    
    // Expects 'Populations' to be in the same directory as the RepAppor class.
    InputStream in = RepAppor.class.getResourceAsStream("Populations/" + fileName);
    
    // Expects 'Populations' to be in the root of the classpath.
    InputStream in = RepAppor.class.getResourceAsStream("/Populations/" + fileName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-03
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多