小编给大家分享一下如何解决SpringBoot项目找不到resources目录下的资源问题,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!springboot项目找不到resources目录下的资源问题描述:将老的mvc项目
小编给大家分享一下如何解决SpringBoot项目找不到resources目录下的资源问题,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
将老的mvc项目转为boot后找不到resources文件夹下的资源文件
war包采用的是Tomcat部署,tomcat会对war包进行解压,以及目录的一些操作。而springboot使用jar包部署,服务器中是不存在相关目录的。
springboot 2.2.2RELAESE
ClassPathResource classPathResource = new ClassPathResource(filePath);InputStream inputStream = classPathResource.getInputStream();
import java.io.File;import java.io.InputStream; import org.apache.commons.io.FileUtils;import org.apache.commons.io.IOUtils;import org.springframework.core.io.ClassPathResource; public class FileUtil { public File getResourceFile(String filePath) throws Exception{ try { ClassPathResource classPathResource = new ClassPathResource(filePath); InputStream inputStream = classPathResource.getInputStream(); //生成目标文件 File somethingFile = File.createTempFile("DailyReportTemplate", ".xls"); try { FileUtils.copyInputStreamToFile(inputStream, somethingFile); } finally { IOUtils.closeQuietly(inputStream); } return somethingFile; } catch (Exception e) { throw new Exception(e); } } }
在idea中运行,一切正常,资源文件都可以访问到,但打成jar包后,使用java -jar的形式去启动,就访问不到resource下的资源文件了
网上搜了很多文章,但试了后都不好使
我的路径是配置在properties文件中,然后读取配置文件中的值,然后拼接文件路径,再使用ClassPathResource去读取的
开始时我配置文件中是这样写的:
#路径中注意首尾不要有空格service.config-root=static/service/service.config-name=AppConfig.JSON
程序代码读出后拼接:
@Value("${service.config-root}")private String configRoot; @Value("${service.config-name}")private String configName; .....省略无关code..... public String getPath(){ String configPath = this.configRoot + this.configName; return configPath;}
但运行jar后,直接FileNotFoundException了
主要是斜杠"\"和反斜杠"/"的问题,配置文件修改如下:
#路径中注意首尾不要有空格service.config-root=static\\tileservice\\service.config-name=AppConfig.json
使用"File.spearator"拼接路径
service.config-root=staticservice.config-name=AppConfig.json@Value("${service.config-root}")private String configRoot; @Value("${service.config-name}")private String configName; .....省略无关code..... public static <T> T readJsonFromClassPath(Type type) throws IOException { //这里使用File.spearator拼接 ClassPathResource resource = new ClassPathResource(this.configRoot + File.spearator + this.configName); if (resource.exists()) { return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type, ..... } }
看完了这篇文章,相信你对“如何解决springboot项目找不到resources目录下的资源问题”有了一定的了解,如果想了解更多相关知识,欢迎关注编程网精选频道,感谢各位的阅读!
--结束END--
本文标题: 如何解决springboot项目找不到resources目录下的资源问题
本文链接: https://www.lsjlt.com/news/300196.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0