SpringBoot 2.1.9.RELEASE-读取资源文件

时间:2019-10-04 08:35:48

标签: java spring spring-boot spring-mvc resources

我想读取资源文件, 这样做很正常:

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

但是当我这样做

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

我收到此错误:

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

1 个答案:

答案 0 :(得分:1)

问题在于声明

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

应该是

new ClassPathResource("files/hostel_resource.json")

使用Spring的classpath读取文件时,无需在文件路径中添加ClassPathResource

Spring内部使用java.lang.ClassLoader来解析文件的完整路径。