Dan
Dan

Reputation: 829

Reading a resource file in Jar

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.

Upvotes: 1

Views: 3462

Answers (1)

jingx
jingx

Reputation: 4014

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)

Upvotes: 3

Related Questions