我想读取资源文件, 这样做很正常:
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
答案 0 :(得分:1)
问题在于声明
new ClassPathResource("classpath:files/hostel_resource.json")
应该是
new ClassPathResource("files/hostel_resource.json")
使用Spring的classpath
读取文件时,无需在文件路径中添加ClassPathResource
Spring内部使用java.lang.ClassLoader
来解析文件的完整路径。