user3326720 user3326720 - 7 months ago 47
Java Question

Getting json resource throws NullPointerException

I've been trying to load my json file (LandInfo) from a res folder within my src folder.

enter image description here

I want to load the file in so that it can be parsed with Gson.

I've tried doing:



new InputStream(getClass().getResourceStream("res/LandInfo"))

since Gson#fromJSon accepts either a string or a reader

However, both options return null.

How would I go about finding the file in a correct manner?


getClass().getResource() loads resources from the directory in which your class is located (here "src/sample") Thus the returned URL by this method would look like "src/sample/res/LandInfo" which is not correct.

Instead, you could use:



new InputStream(getClass().getResourceStream("../res/LandInfo"))

Also make sure that your non-java files (resources) are copied into your build folder when using build managers such as Maven, Gradle, etc