news 2026/4/17 6:18:04

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/3/25 17:36:16

倪海厦谈泄南补北法

仅供参考&#xff0c;不构成任何治病建议&#xff0c;请遵医嘱。 网址&#xff1a;倪海厦谈泄南补北法

作者头像 李华
网站建设 2026/4/12 22:18:51

百考通AI让学术启航从“无从下手”到“一气呵成”

对于每一位即将踏上学术研究征程的学子而言&#xff0c;开题报告是迈入正式研究阶段的第一道也是至关重要的门槛。它不仅是对研究课题的初步规划和论证&#xff0c;更是向导师和评审委员会展示你研究能力与潜力的“敲门砖”。然而&#xff0c;面对空白的文档、模糊的研究方向和…

作者头像 李华
网站建设 2026/4/17 18:45:35

百考通AI任务书功能:智能生成贴合你研究方向的专业任务书,规范高效一步到位

毕业设计任务书是高校教学流程中承前启后的关键环节——它不仅是选题的正式确认&#xff0c;更是后续研究、开发与论文撰写的行动纲领。然而&#xff0c;许多学生在撰写时常常陷入“有想法却写不出”“懂技术但不会表达”“找模板又不匹配”的困境&#xff0c;导致内容空泛、结…

作者头像 李华
网站建设 2026/4/6 12:18:39

Chrome 自动填充“用户名”到普通输入框 - 解决方案

Chrome 自动填充“用户名”到普通输入框&#xff1f;我被 Seller ID 坑了一天 简介 在后台系统或业务表单中&#xff0c;我们经常会遇到一些完全不是登录账号的字段&#xff0c;却被 Chrome 强行自动填充为浏览器保存的用户名或邮箱。 本文将以 Seller ID 输入框被 Chrome 自动…

作者头像 李华