spring boot项目打成jar运行,获取resources目录下的文件失败(文件不存在)

在Spring boot项目源码环境下能正常获取resources目录下的文件,打成jar包运行后获取文件失败,提示找不到文件。

文件所在位置(要获取patch_1.1.sql这个文件):
在这里插入图片描述

以前的获取方式(在本地源码环境可以获取,打成jar包运行后获取失败):

URL url = this.getClass().getResource("/static/upgrade/bpm/patch_1.1.sql");
if (url != null) {
	File file = new File(url.getPath());
	// do something
}

获取文件失败的原因:在本地源码环境是以相对路径或绝对路径的方式获取文件,打成jar包后文件的路径变了,当然获取不到了。

现在的获取方式:

ClassPathResource classPathResource = new ClassPathResource("static/upgrade/bpm/patch_1.1.sql");
if (classPathResource.exists() && classPathResource.isFile()){
	File file = classPathResource.getFile();
	//do something
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在将Spring Boot项目打成jar包后,如果工具类无法读取模板文件,可能是因为模板文件没有被正确地打包进jar包中。这可以通过以下方法解决: 1. 确认模板文件的路径和位置。在Spring Boot项目中,模板文件通常位于/resources/templates目录下。确保文件名和相对路径都正确。 2. 使用Maven插件来打包项目。例如,在pom.xml文件中添加以下配置: ``` <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration> </plugin> </plugins> </build> ``` 3. 将模板文件的位置和路径添加到ResourceLoader中。例如,可以在工具类中使用以下代码来获取模板文件: ``` ResourceLoader resourceLoader = new FileSystemResourceLoader(); Resource resource = resourceLoader.getResource("classpath:/templates/template.html"); ``` 其中,classpath:/templates/template.html是模板文件的相对路径。 4. 如果仍然无法读取模板文件,可以尝试将模板文件打包到jar包的根目录下。在pom.xml文件中添加以下配置: ``` <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> <filtering>true</filtering> </resource> </resources> </build> ``` 这将在打包时将src/main/resources目录下的所有文件打包到根目录下。 综上所述,将Spring Boot项目打包成jar包后,如果工具类无法读取模板文件,需要注意模板文件的路径和位置,并使用Maven插件来打包项目。此外,还可以将模板文件打包到jar包的根目录下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值