0

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?

Orange Receptacle
  • 1,173
  • 3
  • 19
  • 40
  • Try with `/res/LandInfo` since you don't want path related to current location of class returned from `getClass` but from root location of your resources. More info: http://stackoverflow.com/questions/9864267/load-icon-image-exception – Pshemo Aug 03 '16 at 17:27
  • This still throws the same error – Orange Receptacle Aug 03 '16 at 17:29
  • You should use `/LandInfo` as a resource path here; the `res` directory is marked as a directory on the classpath itself according to your image – fge Aug 03 '16 at 17:47
  • I tried that out as well, but it gave me the same result – Orange Receptacle Aug 03 '16 at 17:51
  • As your using intellij, I personally do it like this: 1. Right click on the file in explorer, and click copy file path. Paste the copied file path. – Sarhad Salam Aug 03 '16 at 18:18

1 Answers1

3

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

Erfan Gholamian
  • 225
  • 1
  • 9