Java 在jar文件中包含文本文件并读取它

Java 在jar文件中包含文本文件并读取它,java,jar,nullpointerexception,embedded-resource,Java,Jar,Nullpointerexception,Embedded Resource,可能重复: 我对Java有点陌生,我正在尝试在Jar文件中获取一个文本文件 在执行jar时,我必须将文本文件与jar文件放在同一个文件夹中。如果文本文件不在那里,我将得到一个NullPointerException,这是我想要避免的 我想做的是将txt文件放在jar中,这样我就不会有这个问题。我试过一些指南,但似乎不起作用。我当前的读取功能如下所示: public static HashSet<String> readDictionary() { HashSet<St

可能重复:

我对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;
}
公共静态HashSet readDictionary()
{
HashSet toRet=新的HashSet();
尝试
{
//打开第一个文件
//命令行参数
FileInputStream fstream=新的FileInputStream(“Dictionary.txt”);
try(DataInputStream in=newdatainputstream(fstream)){
BufferedReader br=新的BufferedReader(新的InputStreamReader(in));
弦斯特林;
//逐行读取文件
而((strLine=br.readLine())!=null){
//读台词
添加(斯特林);
}
}
返回托雷特;
}
捕获(例外e)
{//Catch异常(如果有)
System.err.println(“错误:+e.getMessage());
} 
返回null;
}

不要试图在Jar文件中找到作为“文件”的文件。而是使用资源

获取对类或类加载器的引用,然后在类或类加载器上调用
getResourceAsStream(/*资源地址*/)


请参阅下面的类似问题(如果可能,请避免创建新问题):


似乎完全重复了这个问题:

关于
NullPointerException
的问题,我建议不要确保它不会发生,而是做好准备并正确处理它。我会更进一步地要求您始终检查变量的空值,这是一件好事

// add a leading slash to indicate 'search from the root of the class-path'
URL urlToDictionary = this.getClass().getResource("/" + "Dictionary.txt");
InputStream stream = urlToDictionary.openStream();
另见