Nad*_*ern 6 java jar nullpointerexception embedded-resource
可能重复:
Java资源作为文件
我是Java的新手,我试图在Jar文件中获取一个文本文件.
在我执行我的jar时,我必须将我的文本文件放在与jar文件相同的文件夹中.如果文本文件不存在,我会得到一个NullPointerException,我想避免.
我想要做的是在jar中获取txt文件,所以我不会遇到这个问题.我尝试了一些指南,但它们似乎没有用.我目前的读取功能如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
不要试图在Jar文件中找到文件作为"文件".请改用资源.
获取对类或类加载器的引用,然后在类或类加载器调用上getResourceAsStream(/* resource address */);.
你也应该研究你的搜索技巧,因为这里已经被无数次地询问和回答了.事实上,我们可能应该关闭这个问题,因为我没有看到它增加了已经出现在SO上的讨论.
| 归档时间: |
|
| 查看次数: |
22873 次 |
| 最近记录: |