问题
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