spring boot项目正确读取项目资源文件
maven项目:资源文件放在src/main/resources IDE调试时未打包:资源文件放在target/classes中 非spring boot的瘦包,资源文件放在xxx.jar包的根下。 spring boot肥包,资源文件放在xxx.jar包下的BOOT-INF\classes\中。
org.springframework.core.io.ClassPathResource 支持IDE时的未打包资源,和瘦包。不支持Spring boot可运行的肥包。 org.springframework.core.io.DefaultResourceLoader 支持IDE时的未打包资源,和瘦包。还支持Spring boot可运行的肥包。
Spring Boot 项目读取jar的资源文件:
org.springframework.core.io.DefaultResourceLoader
try (InputStream stream = new DefaultResourceLoader().getResource(path).getInputStream()) {
byte[] byteArray = new byte[stream.available()];
stream.read(byteArray);
return new String(byteArray);
}