user3326720 user3326720 - 4 months ago 22
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:

getClass().getResource("res/LandInfo").toExternalForm()


and

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?

Answer

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:

getClass().getResource("../res/LandInfo").toExternalForm()

and

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