news 2026/1/17 18:24:50

SpringBoot下获取resources目录下文件的常用方法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot下获取resources目录下文件的常用方法

哈喽,大家好,今天给大家带来SpringBoot获取resources目录下文件的常用方法,示例中的方法是读取resources目录下的txt和xlsx文件,并将xlsx导出到excel的简单写法。完整代码放在最后。

通过this.getClass()方法获取

method1 - method4都是通过这个方法获取文件的写法,这四种写法在idea中都可以正常运行,jar包执行后method1和method2报错,提示找不到文件,method3和method4可以正常运行

通过ClassPathResource获取

method5是通过这种方法实现,idea中可以正常运行,打包后的jar中提示找不到文件

通过hutool工具类ResourceUtil获取

method6是通过这种方法实现,和method情况一样,同样是idea中可以正常运行,导出的jar中提示找不到文件

总结

不想折腾的同学可以直接用method3和method4的方法来使用,也可以将模板和资源文件外置,通过绝对路径获取对应文件。有好的方法也欢迎大家一起交流沟通~

代码

import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.resource.ClassPathResource; import cn.hutool.core.io.resource.ResourceUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.enums.WriteDirectionEnum; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.fill.FillConfig; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.List; @RestController @RequestMapping("/temp") public class TemplateController { /** * this.getClass()方法获取 * @param response * @throws IOException */ @RequestMapping("/method1") public void method1(HttpServletResponse response) throws IOException { System.out.println("----------method1 start"); String filename = "template.xlsx"; String bashPatch = this.getClass().getClassLoader().getResource("").getPath(); System.out.println(bashPatch); String textFile = "template.txt"; String textPath = this.getClass().getClassLoader().getResource("").getPath(); List<String> dataList = FileUtil.readUtf8Lines(textPath + "/template/" + textFile); for (String data : dataList) { System.out.println(data); } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 // .withTemplate(resource.getFile().getAbsolutePath()) .withTemplate(bashPatch + "/template/" + filename) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } @RequestMapping("/method2") public void method2(HttpServletResponse response) throws IOException { System.out.println("----------method2 start"); String filename = "template.xlsx"; String bashPatch = this.getClass().getClassLoader().getResource("template").getPath(); System.out.println(bashPatch); String textFile = "template.txt"; String textPath = this.getClass().getClassLoader().getResource("template").getPath(); List<String> dataList = FileUtil.readUtf8Lines(textPath + "/" + textFile); for (String data : dataList) { System.out.println(data); } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 // .withTemplate(resource.getFile().getAbsolutePath()) .withTemplate(bashPatch + "/" + filename) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } @RequestMapping("/method3") public void method3(HttpServletResponse response) throws IOException { System.out.println("----------method3 start"); String filename = "template.xlsx"; InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template" + "/" + filename); // System.out.println(inputStream); String textFile = "template.txt"; InputStream textStream = this.getClass().getClassLoader().getResourceAsStream("template" + "/" + textFile); BufferedReader reader = new BufferedReader(new InputStreamReader(textStream)); String line; try { while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); // 异常处理 } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 // .withTemplate(resource.getFile().getAbsolutePath()) .withTemplate(inputStream) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } @RequestMapping("/method4") public void method4(HttpServletResponse response) throws IOException { System.out.println("----------method4 start"); String filename = "template.xlsx"; InputStream inputStream = this.getClass().getResourceAsStream("/template" + "/" + filename); // System.out.println(inputStream); String textFile = "template.txt"; InputStream textStream = this.getClass().getResourceAsStream("/template" + "/" + textFile); BufferedReader reader = new BufferedReader(new InputStreamReader(textStream)); String line; try { while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); // 异常处理 } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 // .withTemplate(resource.getFile().getAbsolutePath()) .withTemplate(inputStream) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } /** * 通过ClassPathResource获取 * @param response * @throws IOException */ @RequestMapping("/method5") public void method5(HttpServletResponse response) throws IOException { System.out.println("----------method5 start"); String filename = "template.xlsx"; ClassPathResource classPathResource = new ClassPathResource("template" + "/" + filename); String textFile = "template.txt"; ClassPathResource textResource = new ClassPathResource("template" + "/" + textFile); List<String> dataList = FileUtil.readUtf8Lines(textResource.getAbsolutePath()); for (String data : dataList) { System.out.println(data); } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 .withTemplate(classPathResource.getAbsolutePath()) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } /** * 通过hutool工具类ResourceUtil获取 * @param response * @throws IOException */ @RequestMapping("/method6") public void method6(HttpServletResponse response) throws IOException { System.out.println("----------method6 start"); String filename = "template.xlsx"; String filePath = ResourceUtil.getResource("template" + "/" + filename).getPath(); String textFile = "template.txt"; String textPath = ResourceUtil.getResource("template" + "/" + textFile).getPath(); List<String> dataList = FileUtil.readUtf8Lines(textPath); for (String data : dataList) { System.out.println(data); } try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()) .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理 .withTemplate(filePath) .build() ) { WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); excelWriter.finish(); } try { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } }

pom依赖

编程语言C++m.jingdaocn.com++c语言的魅力
编程语言C++m.tianfuyoushi.com++c语言的魅力
编程语言C++m.lijidecoration.com++c语言的魅力
编程语言C++m.xingyuanad.com++c语言的魅力
编程语言C++m.ezeghr.com++c语言的魅力
编程语言C++m.zgyglp.com++c语言的魅力
编程语言C++m.lazipig.net++c语言的魅力
编程语言C++m.fzdzjzs.com++c语言的魅力
编程语言C++m.happystudio.cn++c语言的魅力
编程语言C++m.jtlspray.com++c语言的魅力
编程语言C++m.hnrjhnt.cn++c语言的魅力
编程语言C++m.wxrsjh.com++c语言的魅力
编程语言C++www.yuehanjianzhu.cn++c语言的魅力
编程语言C++www.blog.yuehanjianzhu.cn++c语言的魅力
编程语言C++www.share.yuehanjianzhu.cn++c语言的魅力
编程语言C++read.share.yuehanjianzhu.cn++c语言的魅力
编程语言C++m.yuehanjianzhu.cn++c语言的魅力
编程语言C++www.mingkejiaoyu.com.cn++c语言的魅力
编程语言C++www.blog.mingkejiaoyu.com.cn++c语言的魅力
编程语言C++www.share.mingkejiaoyu.com.cn++c语言的魅力
编程语言C++read.share.mingkejiaoyu.com.cn++c语言的魅力
编程语言C++m.mingkejiaoyu.com.cn++c语言的魅力

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/1/17 18:14:40

鸿蒙6访问内网域名异常排查

最近接到用户反馈&#xff0c;使用mate60pro升级到鸿蒙6.0版本后&#xff0c;访问校内应用异常&#xff0c;无法打开校内应用。 与用户了解情况如下&#xff1a; 手机型号&#xff1a;华为mate60pro 系统版本&#xff1a;6.0.0.120(SP6C00E120R4P11patch12) 正常获取了内网地址…

作者头像 李华
网站建设 2026/1/17 18:12:16

双碳目标下的 “绿色算力”—— 云服务器如何实现节能与性能双赢​

在 “双碳” 目标引领下&#xff0c;绿色低碳成为各行业发展的核心主题。云计算作为数字经济的核心基础设施&#xff0c;其能耗问题日益受到关注。数据显示&#xff0c;全球数据中心的能耗约占全球总用电量的 1.5%&#xff0c;而云服务器作为数据中心的核心设备&#xff0c;其节…

作者头像 李华
网站建设 2026/1/17 18:11:13

猫狗识别人工智能代码基于深度学习的猫狗识别系统完整源码+数据集+项目报告(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码

猫狗识别人工智能代码基于深度学习的猫狗识别系统完整源码数据集项目报告(设计源文件万字报告讲解)&#xff08;支持资料、图片参考_相关定制&#xff09;_文章底部可以扫码 yolov5yolov8目标检测算法模型大学生大作业用Python语言实现&#xff0c;深度学习和图像处理技术&…

作者头像 李华
网站建设 2026/1/17 18:10:54

基于逻辑回归模型的贷款违约预测(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码

基于逻辑回归模型的贷款违约预测(设计源文件万字报告讲解)&#xff08;支持资料、图片参考_相关定制&#xff09;_文章底部可以扫码 Python大数据分析商业分析商业数据分析机器学习数据可视化 jupyter数据分析项目 [绿圆]贷款违约预测 [绿圆]逻辑回归模型 Python分析报告项目&a…

作者头像 李华
网站建设 2026/1/17 18:06:14

告别查重焦虑,重塑学术尊严

在人工智能技术飞速发展的今天&#xff0c;学术写作的边界正在被重新定义。一方面&#xff0c;AI工具极大地提升了我们的创作效率&#xff1b;另一方面&#xff0c;随之而来的“AI生成痕迹”和“高重复率”问题&#xff0c;却成为横亘在无数学子、研究者面前的一道巨大鸿沟。当…

作者头像 李华
网站建设 2026/1/17 18:06:12

一键生成专业文献综述

在浩如烟海的学术文献中&#xff0c;如何高效地梳理前人成果、精准定位研究空白&#xff0c;是每一位研究者面临的首要挑战。撰写一篇高质量的文献综述&#xff0c;不仅需要广博的阅读量&#xff0c;更需要强大的信息整合与批判性思维能力。这个过程往往耗时费力&#xff0c;令…

作者头像 李华