jar文件没有正确查找文件

时间:2021-01-23 18:04:28

I have spent the past 3 nights going crazy trying to find an answer to this. So I have a java program and I want it to be in a jar format and I want it to be able to read in text and image files.
I got the image files working fine using the this.getClass.getResource("") method, however I can not get the program to properly access the text files within the .jar, When I extract the jar, the text files are there so I know It is not a simple mistake of the text files not being within the jar

过去3个晚上我一直疯狂地试图找到答案。所以我有一个java程序,我希望它是一个jar格式,我希望它能够读取文本和图像文件。我使用this.getClass.getResource(“”)方法使图像文件正常工作,但我无法让程序正确访问.jar中的文本文件,当我解压缩jar时,文本文件就在那里我知道文本文件不在jar中并不是一个简单的错误

This is what I tried using, but it didn't work(It works without a jar, but now within a jar)

这是我尝试使用的,但它没有用(它没有jar,但现在在jar中)

URL lurl = this.getClass().getResource("list.txt");
BufferedReader in3 = new BufferedReader(new FileReader(lurl.getFile()));

Fixes?

修复?

1 个解决方案

#1


1  

Assuming your class is

假设你的班级是

my.package.MyClass

The method will read the file from directory /my/package from JAR.

该方法将从JAR中的目录/ my / package读取文件。

You can open the resource via:

您可以通过以下方式打开资源:

BufferedReader in3 = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("list.txt")));

#1


1  

Assuming your class is

假设你的班级是

my.package.MyClass

The method will read the file from directory /my/package from JAR.

该方法将从JAR中的目录/ my / package读取文件。

You can open the resource via:

您可以通过以下方式打开资源:

BufferedReader in3 = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("list.txt")));