gpt4 book ai didi

java - 确保 JAR 中包含文本文件

转载 作者:行者123 更新时间:2023-12-02 11:06:06 24 4
gpt4 key购买 nike

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

我一直在尝试将项目导出为 JAR 文件,其中包括从文本文件中读取信息。做了一些之后research ,我将阅读器从 FileReader 更改为 InputStreamReader,使用 CLASSNAME.class.getClassLoader().getResourceAsStream("textFile.txt") 。 (我也知道它应该在不涉及 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);
}
}

感谢您的考虑,我感谢并欢迎您提供任何反馈。

最佳答案

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

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

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

jar tf /Users/AaronMoriak/repappor.jar

每个 .jar 文件实际上都是一个具有不同扩展名(以及一个或多个 Java 特定的特殊条目)的 zip 文件。因此,任何处理 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);

关于java - 确保 JAR 中包含文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50954618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com