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)));
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().
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With