0

I'm trying to read a json file in a Resources directory and I use the following:

jsonObject = this.readJson(this.getClass().getClassLoader().getResource("jsonFileName").getPath());

In the IDE it runs correctly but when I build thw jar and try to run it by java -jar jarName I get a "File not found" Error and when I checked the path, it looks like this:

...projectName/target/projectName-1.0-SNAPSHOT.jar!/kb/is/identity.json

When running on the IDE the paths looks like this:

...projectName/target/classes/kb/is/identity.json

S.Dan
  • 1,826
  • 5
  • 28
  • 55

2 Answers2

2

getResource("jsonFileName") - in this case root directory is project name using it under Idea, but when you run it under jar - I think that root path is User Home.

If I remember correctly, you can fix it with using / in resource path. E.g. when using Maven, you have a resource directory. You have identity.json in the resource root. Using getClass().getResourceAsStream("/identity.json") receive this file (in Idea and in jar), because when you build a jar, all resources are copied to the root of the jar file.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • `getResourceAsStream` actually worked but without `getClassLoader` it gave out an error. – S.Dan Jan 31 '18 at 08:45
2

It's important to use getResourceAsStream, not getResource. Have a look at How getClassLoader().getResourceAsStream() works in java

Daniel
  • 1,494
  • 9
  • 9