Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top