Reading files from in a jar

Getting a java.io.FileNotFoundException when trying to load a resource. This didn’t occur when running the code from the IDE but when it was deployed.

The culprit was getClass().getResource(“filename”), which returns a url. I then created a BufferedReader from a FileReader, from a File, from the url, phew.

What I think happens in that the wrong handler get used, java assumes you are trying to read a normal file from the filesystem and uses the file protocol handler, when in fact you need the jar protocol handler.

FIX

InputStream inputStream = getClass().getResourceAsStream("fileName");
reader = new BufferedReader(new InputStreamReader(inputStream));

About this entry