【发布时间】:2012-05-14 05:36:55
【问题描述】:
我是 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