Sandro Rey
Sandro Rey

Reputation: 2989

SpringBoot 2.1.9.RELEASE - reading resource file

I want to read a resouce file, doing this it works fine:

HostelPayload hostelPayload = objectMapper.readValue(new File("C:/Users/sandro/IdeaProjects/bendiciones/src/test/resources/files/hostel_resource.json"), HostelPayload.class);

but when I do this

Resource resource = new ClassPathResource("classpath:files/hostel_resource.json");
HostelPayload hostelPayload = objectMapper.readValue(resource.getFile(), HostelPayload.class);

I got this error:

java.io.FileNotFoundException: class path resource [classpath:files/hostel_resource.json] cannot be resolved to URL because it does not exist

Upvotes: 0

Views: 214

Answers (1)

isank-a
isank-a

Reputation: 1675

The problem is the statement

new ClassPathResource("classpath:files/hostel_resource.json")

It should be just

new ClassPathResource("files/hostel_resource.json")

You don't need to add classpath to file paths when reading files using Spring's ClassPathResource

Spring internally uses java.lang.ClassLoader to resolve the complete path of the file.

Upvotes: 1

Related Questions