How to read a Json file under the resources folder?
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 isderived from the subsequence of characters that precedes the last '/'in the name and then replacing each '/' character in the subsequencewith '.'. 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")
.
There are two possibilities here.
- Not Packaged, Not Found
- 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