Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a resource with BufferedReader

I am trying to read a resource that will be included into a .JAR, but I get a nullPointer for the following:

bReader = new BufferedReader(new InputStreamReader(
                  this.getClass().getResourceAsStream("resources/" + fileName)));

Using a File however, works fine..

bReader = new BufferedReader(new FileReader(new File("resources/" + fileName)));
like image 936
Skogen Avatar asked Mar 03 '13 17:03

Skogen


People also ask

How do I read a resource file?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

How do I view the resources folder in a jar file?

This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .

How does BufferedReader readLine work?

Class BufferedReader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.


1 Answers

Assuming your IDE/Maven/ANT/Gradle/build process will include contents of "resources" in jar at root, try finding it at "/".

bReader = new BufferedReader(new InputStreamReader(
                           this.getClass().getResourceAsStream("/" + fileName)));

UPDATE:

Make sure the "resources" folder is configured as a resource folder.

like image 53
sgp15 Avatar answered Sep 22 '22 22:09

sgp15