Reputation: 851
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
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:
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))
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