Exporting a JAR with Ressources

二次信任 提交于 2019-12-11 11:28:41

问题


I was trying to solve this problem the whole day but in vain !!

Basically I want to export a JAR with images and a txt file (and latter maybe an audio file).

I found that I need to make a new folder within I should add my resources, I did.

then I found that I should use something like :

pan.add(new JLabel(new ImageIcon(getClass().getResource("/131868.jpg"))));

instead of pan.add(new JLabel(new ImageIcon("/131868.jpg"))); I did

but for my text file

BufferedReader br = new BufferedReader(new FileReader("dictionnaire.txt"));

I used BufferedReader br = new BufferedReader(new FileReader((getClass().getResource("dictionnaire.txt")).toString)); but I get a NullPointerException

and without it, when I make the JAR file and open it as rar I don't find my resource folder !!!! SOS


回答1:


An embedded resources can not be treated like a File, don't think of it like a file, it will only confuse you more, it is a "resource" and needs to be treated differently

Instead of

BufferedReader br = new BufferedReader(new FileReader("dictionnaire.txt"));

or

BufferedReader br = new BufferedReader(new FileReader((getClass().getResource("dictionnaire.txt")).toString)); 

You will need to use something like...

BufferedReader br = new BufferedReader(
    new InputStreamReader(getClass().getResourceAsStream("dictionnaire.txt"));

Class#getResource will return a URL, many objects are happy to deal with a URL, but it can be messy having to get a URL's InputStream, so Class#getResourceAsStream makes it easier to achieve this in a single call



来源:https://stackoverflow.com/questions/21128053/exporting-a-jar-with-ressources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!