当前位置: 首页 > news >正文

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语言的魅力

http://www.jsqmd.com/news/259063/

相关文章:

  • Java面试场景:互联网大厂如何考核Spring Boot与Kafka应用能力
  • ChatGPT是怎么学会接龙的?
  • 学习进度三:实验 3 Spark 和 Hadoop 的安装
  • 209_尚硅谷_继承快速入门应用实例
  • 【软考环境架构设计师】四、信息系统基础知识
  • wsl的网络模式有哪几种,有哪些区别?
  • Java企业AI转型实录:JBoltAI破解智能问答系统开发
  • 轻量级云文件系统simple-file-server,电脑秒变存储服务器
  • JBoltAI的AI应用中台:构建企业智能化的坚实基础
  • 企业上云转型的 “压舱石”—— 云服务器如何破解中小微企业数字化痛点​
  • 基于逻辑回归模型的贷款违约预测(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 一键生成专业文献综述
  • 数字经济的 “安全基石”—— 云服务器零信任架构如何筑牢数据安全防线​
  • 基于多模型比较的慢性肾病分类模型设计与优化研究(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 鸿蒙6访问内网域名异常排查
  • 2026.1.17HCSA第二次作业
  • 2026必备!本科生毕业论文AI论文网站TOP9测评
  • Node.js用crypto.createCipheriv流式加密优化
  • 猫狗识别人工智能代码基于深度学习的猫狗识别系统完整源码+数据集+项目报告(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 基于深度学习的车辆检测系统(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • AI 大模型时代的 “算力引擎”—— 云服务器如何支撑智能应用规模化落地​
  • 基于YOLOv5的葡萄叶片病虫害识别(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 双碳目标下的 “绿色算力”—— 云服务器如何实现节能与性能双赢​
  • 百考通AI让复杂数据从“沉默的数字”到“决策的金矿”
  • 基于python机器学习的二手房数据分析(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 基于Hadoop的电商推荐系统有报告(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 百考通AI任务书功能:精准理解你的课题,智能输出专业级毕业设计任务书
  • 百考通AI任务书功能:智能生成结构完整、内容规范的毕业设计任务书
  • 基于python的电商订单数据可视化分析预测研究项目(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 下载 | Win11 25H2 正式版1月更新!(系统ISO映像、年度更新版本、26200.7623、Windows 11)