spring boot 项目打成jar包后读取文件问题
程序员文章站
2022-04-28 09:09:39
...
java.io.FileNotFoundException: class path resource [xxx.xls]
cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/新建文件夹/xxx.jar!/BOOT-INF/classes!/export/xxx.xls
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)
在war包运行情况下是没问题的,路径其实是对的,spring是不允许直接访问jar包内的文件的,所以会报错,然后改写下读取文件的方式
-
精简的老代码方式
ClassPathResource resource = new ClassPathResource("XXX.xls"); File file = resource.getFile();
-
修改后的精简代码
ClassPathResource resource = new ClassPathResource("application.yml"); InputStream inputStream = resource.getInputStream();
-
笔者老代码
public String generateExcel(String sourceFileName, String destFileName, Map<String, Object> params) throws Exception{ XLSTransformer transformer = new XLSTransformer(); // URL url = this.getClass().getClassLoader().getResource(""); // // assert url != null; ClassPathResource resource = new ClassPathResource(EXPORT_RESOURCE_PATH + sourceFileName); transformer.transformXLS( resource.getFile().getPath(), params, TMP_DIR + destFileName); return TMP_DIR + destFileName; }
-
笔者新代码
public String generateExcel(String sourceFileName, String destFileName, Map<String, Object> params) throws Exception{ // XLSTransformer transformer = new XLSTransformer(); // URL url = this.getClass().getClassLoader().getResource(""); // // assert url != null; ClassPathResource resource = new ClassPathResource(EXPORT_RESOURCE_PATH + sourceFileName); InputStream inputStream = resource.getInputStream(); // transformer.transformXLS( resource.getFile().getPath(), params, TMP_DIR + destFileName); transformXLS4Jar( inputStream, params, TMP_DIR + destFileName); return TMP_DIR + destFileName; } public void transformXLS4Jar(InputStream is, Map beanParams, String destFilePath) throws ParsePropertyException, IOException, InvalidFormatException { XLSTransformer xlsTransformer = new XLSTransformer(); org.apache.poi.ss.usermodel.Workbook workbook = xlsTransformer.transformXLS(is, beanParams); OutputStream os = new BufferedOutputStream(new FileOutputStream(destFilePath)); workbook.write(os); is.close(); os.flush(); os.close(); }
推荐阅读
-
解决SpringBoot打成jar运行后无法读取resources里的文件问题
-
关于Springboot打成JAR包后读取外部配置文件的问题
-
spring boot集成easyexcel解决jar包无法获取文件问题
-
Spring Boot打jar包后配置文件的外部优化配置方法
-
解决SpringBoot打成jar运行后无法读取resources里的文件问题
-
spring boot 读取resources下文件 和 打成jar 读取jar包中配置文件
-
Spring Boot工程打完jar包读取工程内的模板文件
-
【问题解决】解决项目打包成jar包,部署上线后,读取resources目录文件资源失效。
-
SpringBoot项目打成jar包后resource下文件的读取
-
spring boot项目打成jar包后,classespath路径获取错误