【发布时间】: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);
}
}
感谢您的考虑,感谢并欢迎您提出任何反馈意见。
【问题讨论】: