1

I am using IntelliJ Idea and trying to read a json file from the resources folder in the project structure. I read the json file and return the contents using jackson.

return mapper.readValue(File("src/main/resources/file.json"), Map::class.java)

As soon i build the project and make a jar it throws me an error it cannot find the file. I looked here a bit and found that i should use ClassLoader to read files from the resources folder. So i do this now -

mapper.readValue(File( ClassLoader.getSystemClassLoader().getResource("src/main/resources/file.json").toURI()), Map::class.java)

Now I get a NullPointerException. I am a bit lost now. Any help is deeply appreciated.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dan
  • 801
  • 2
  • 14
  • 29
  • You cannot read a file inside a jar as a normal text file, as per: https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar – Arlo Guthrie Jun 14 '18 at 13:46
  • What is `mapper`? Is it an [`ObjectMapper`](https://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/ObjectMapper.html)? – Andrew Thompson Jun 14 '18 at 14:27
  • @AndrewThompson - yes it is an ObjectMapper. – Dan Jun 14 '18 at 18:52

1 Answers1

3

Assuming your build follows the default convention, whatever under src/main/resource will be available on the root of the classpath, so you just need to change the code to:

mapper.readValue(ClassLoader.getSystemClassLoader().getResourceAsStream("file.json"), Map::class.java)
jingx
  • 3,698
  • 3
  • 24
  • 40
  • somehow doesnt work. throws an error stating - No content to map due to end-of-input\n at [Source: UNKNOWN; line: 1, column: 0. I tried the same with getResource instead of getResourceAsStream as well but that fails as well – Dan Jun 14 '18 at 19:16
  • the getResource("file.json").file throws the following error - ClassLoader.getSystemCla…Resource(\"file.json\") must not be null – Dan Jun 14 '18 at 19:29
  • The path to the resource is more likely `/main/resources/file.json` but only you could know for sure. – Andrew Thompson Jun 15 '18 at 03:17
  • under the root - the file is under src/main/resources/metadata.json – Dan Jun 15 '18 at 08:17
  • Ok for clarification - Whenever i have a file to read in the src/main/resource folder after build(using Gradle) does it always goes to the root? can this not be changed somehow? – Dan Jun 15 '18 at 11:34
  • Ok. strange but this works somehow - `mapper.readValue(javaClass.classLoader.getResource("file.json"), Map::class.java)` – Dan Jun 15 '18 at 14:29