A srinivas
A srinivas

Reputation: 851

Getting nullpointerexception while reading file from resource folder

I am getting NullpointerException when I try to read the file present in src/main/resources location. It occurs when I run in jar format. But when I compile the code and run it , its running fine in Intellij.

Note: I am using sbt package to build the jar and running it.

Please help out. thanks!

Upvotes: 2

Views: 2298

Answers (1)

Markus Appel
Markus Appel

Reputation: 3238

Files that have been packed into the JAR are not accessible from the file system anymore. This can be seen when looking at the URL returned from myClass.getResource("file.txt"), e.g.:

/home/sria/cde-spark-assembly-1.0.jar!/file.txt

Note the ! denoting that the file is packaged into the JAR.


This means you always have to access resource files using the following pattern:

For a file in src/main/resources/file.txt:

myClass.getResourceAsStream("file.txt")

There is two reasons why you might not want to do that:

  1. Adding files to the resources directory will increase the JAR file size.
  2. The file cannot be accessed using standard file system operations.

As an alternative you can load the file from a (configurable) path in the file system, using for example:

val inputStream = new BufferedInputStream(new FileInputStream(myPath))

(reference)

This way you can load a file, e.g. relative to the JAR file path or the execution directory.


I hope this helps.

Note: Both sbt package and sbt assembly will package resource files into the JAR.

Upvotes: 2

Related Questions