news 2026/5/15 23:56:56

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/5/10 17:10:26

ChatGPT是怎么学会接龙的?

ChatGPT是怎么学会接龙的&#xff1f;揭秘大模型训练的第一课 你有没有想过&#xff0c;ChatGPT是怎么学会一个词接一个词地说话的&#xff1f;当你问它"今天天气怎么样"&#xff0c;它为什么能流畅地回答"今天天气晴朗&#xff0c;温度适中&#xff0c;很适合外…

作者头像 李华
网站建设 2026/4/24 23:33:33

Node.js用crypto.createCipheriv流式加密优化

&#x1f493; 博客主页&#xff1a;瑕疵的CSDN主页 &#x1f4dd; Gitee主页&#xff1a;瑕疵的gitee主页 ⏩ 文章专栏&#xff1a;《热点资讯》 Node.js流式加密优化&#xff1a;突破内存瓶颈与实时数据处理目录Node.js流式加密优化&#xff1a;突破内存瓶颈与实时数据处理 …

作者头像 李华
网站建设 2026/5/13 13:48:01

基于python机器学习的二手房数据分析(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码

基于python机器学习的二手房数据分析(设计源文件万字报告讲解)&#xff08;支持资料、图片参考_相关定制&#xff09;_文章底部可以扫码 机器学习房价预测(2025新数据集&#xff0c;python大数据分析&#xff0c;数据可视化机器学习jupyternotebookpython电子资料) 报告代码数据…

作者头像 李华
网站建设 2026/5/15 0:19:36

2026.1.17HCSA第二次作业

1、文件查看&#xff1a;查看/etc/passwd文件的第5行[rootserver ~]# head -5 /etc/passwd | tail -1 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin2、文件查找 (1)在当前目录及子目录中&#xff0c;查找大写字母开头的txt文件[rootserver ~]# find . -name "[A-Z]*.txt&quo…

作者头像 李华
网站建设 2026/5/14 9:05:04

吐血推荐10个AI论文网站,专科生毕业论文轻松搞定!

吐血推荐10个AI论文网站&#xff0c;专科生毕业论文轻松搞定&#xff01; 论文写作不再难&#xff0c;AI工具助你轻松应对 随着人工智能技术的不断发展&#xff0c;越来越多的专科生开始关注并依赖AI工具来辅助自己的论文写作。这些工具不仅能够帮助学生快速生成初稿&#xff0…

作者头像 李华