在 jar 文件中包含一个文本文件并读取它 [英] Including a text file inside a jar file and reading it
问题描述
可能的重复:
Java 资源作为文件
我对 Java 有点陌生,我正在尝试在 Jar 文件中获取一个文本文件.
I am kind of new to Java and I am trying to get a text file inside a Jar file.
在执行 jar 时,我必须将文本文件与 jar fil 放在同一文件夹中.如果文本文件不存在,我将收到 NullPointerException
,我想避免这种情况.
At the moment when I execute my jar I have to have my text file in the same folder as the jar fil. If the text file is not there I'll get a NullPointerException
, which I want to avoid.
我想要做的是将 txt 文件放入 jar 中,这样我就不会遇到这个问题了.我尝试了一些指南,但它们似乎不起作用.我目前的读取功能是这样的:
What I want to do is to get the txt file inside the jar so I wont have this problem. I tried some guides but they didn't seem to work. My current read function goes like this:
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;
}
推荐答案
不要试图在 Jar 文件中查找作为文件"的文件.改用资源.
Don't try to find a file as a "file" in a Jar file. Use resources instead.
获取对类或类加载器的引用,然后在类或类加载器上调用 getResourceAsStream(/* 资源地址 */);
.
Get a reference to the class or class loader and then on the class or class loader call getResourceAsStream(/* resource address */);
.
请参阅下面的类似问题(尽可能避免创建新问题):
See similar questions below (avoid creating new questions if possible):
这篇关于在 jar 文件中包含一个文本文件并读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!