Springboot报class path resource [xxxxx.json] cannot be resolved to URL because it dose not exist问题解决
当Springboot解析resources文件下的json文件时,在本地环境好用,部署到服务器上找不到文件内容 报错class path resource [xxxxx.json] cannot be resolved to URL because it dose not exist
问题排查
(1)pom.xml文件配置
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.json</include> </includes> </resource> <resource> <directory>src/main/another-resources</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
(2)解析classpath下的文件时,要以流的方式去读取,否则打包后读取不到(此种方式本地和服务器都支持)
import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @Service public class FileService { public String readFileFromResourcesFolder() throws IOException { Resource resource = new ClassPathResource("data.txt"); try (InputStream inputStream = resource.getInputStream()) { byte[] bdata = FileCopyUtils.copyToByteArray(inputStream); return new String(bdata, StandardCharsets.UTF_8); } } }
(3)以下解析文件方式(本地支持,服务器不支持)
Resource resource = new ClassPathResource("data.txt"); File f = resource.getFile(); String st = FileUtils.readFileToString(f,Charset.defaultCharset());