How to read a Json file under the resources folder?

1.4k views Asked by At

In my SpringBoot application I have to read a Json file at this path src/main/resources/mock/fileName.json. I done it in this way

JsonReader jsonReaderStream = new JsonReader(new InputStreamReader(Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResourceAsStream("./mock/fileName.json"))));

It works locally but when I deploy my docker file on Kubernetes and I try to read my Json file I received a NullPointerException. I use gradle for the build. I state that I am a beginner on gradle, docker and kubernetes.

Can anyone explain to me why it works locally but not on Kubernetes ?

2

There are 2 answers

0
justthink On BEST ANSWER

There are two possibilities here.

  1. Not Packaged, Not Found
  2. Packaged, Not Found

Go into the .jar package, and check if your mock/x.json exists in target\example.jar!\BOOT-INF\classes.

If it is being packaged but not found, see this answer.
new ClassPathResource("./mock/fileName.json") and then use resource.getInputStream().


I strongly recommend you to place these static json files under resources/static/, so you can directly have these files such as resources/static/mock/a.json, as being requested as /mock/a.json

0
Bjørn Vester On

It looks like you are trying to supply a file path to the method getResourceAsStream, but it doesn't take one. The JavaDoc isn't great and you have to piece different docs together to understand it, but here are some of the relevant parts:

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.

[...]

In the above, the package name for a resource is derived from the subsequence of characters that precedes the last '/' in the name and then replacing each '/' character in the subsequence with '.'. A leading slash is ignored when deriving the package name. As an example, the package name derived for a resource named "a/b/c/foo.properties" is "a.b.c".

So to find your resource on the classpath in a running system, drop the ./ part so it just reads: .getResourceAsStream("mock/fileName.json").