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.mzph.cn/news/1174435.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

吐血推荐!8款AI论文写作软件测评:本科生毕业论文全攻略

吐血推荐&#xff01;8款AI论文写作软件测评&#xff1a;本科生毕业论文全攻略 2026年AI论文写作工具测评&#xff1a;精准筛选&#xff0c;高效助力本科毕业论文 在当前高校教育环境中&#xff0c;本科生撰写毕业论文面临着诸多挑战&#xff0c;包括选题构思困难、文献资料繁杂…

Java面试场景:互联网大厂如何考核Spring Boot与Kafka应用能力

场景&#xff1a;互联网大厂Java小白求职者面试 超好吃是一位刚毕业的Java程序员&#xff0c;今天他来到了某互联网大厂参加面试&#xff0c;面试官是技术专家刘老师。以下是他们的对话&#xff1a;第一轮问题&#xff1a;Spring Boot与Web开发基础 面试官&#xff1a; “超好吃…

第六篇:告别 setInputAction_XXX!我们给地球装上“事件总线”

View Post第六篇:告别 setInputAction_XXX!我们给地球装上“事件总线”本专栏旨在手把手带你从零开始,基于开源三维地球引擎 **Cesium** 封装一套功能完善、可复用的 **WebGIS 增强型 SDK**。内容涵盖核心封装思路、…

学习进度三:实验 3 Spark 和 Hadoop 的安装

学习进度三:实验 3 Spark 和 Hadoop 的安装1.安装 Hadoop 和 Spark2.HDFS 常用操作3. Spark 读取文件系统的数据 准备工作(1)在 spark-shell 中读取 Linux 系统本地文件“/home/hadoop/test.txt ”,然后统计出文…

209_尚硅谷_继承快速入门应用实例

209_尚硅谷_继承快速入门应用实例1.面向对象编程---快速入门案例和继承带来的便利 2.面向对象编程---案例代码 3.面向对象编程---案例输出

【软考环境架构设计师】四、信息系统基础知识

【软考环境架构设计师】四、信息系统基础知识pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &qu…

ChatGPT是怎么学会接龙的?

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

wsl的网络模式有哪几种,有哪些区别?

WSL2(从WSL 2.0.0开始)提供了四种网络模式,它们在网络可见性和配置方式上有明显区别,可以根据自己的开发需求进行选择和配置。为了快速了解,我整理了一张对比表格:模式 核心描述 访问方式 典型场景NAT 默认模式。…

Java企业AI转型实录:JBoltAI破解智能问答系统开发

在AI技术浪潮的推动下&#xff0c;Java企业纷纷踏上智能化转型之路在AI技术浪潮的推动下&#xff0c;Java企业纷纷踏上智能化转型之路&#xff0c;旨在通过AI应用开发提升业务效率和用户体验。我们公司也紧跟时代步伐&#xff0c;决定开发一款智能问答系统&#xff0c;以提供更…

轻量级云文件系统simple-file-server,电脑秒变存储服务器

Simple File Server 一个简单的文件服务器&#xff0c;使用 Go 和 Gin 框架构建&#xff0c;支持文件上传、下载和静态文件服务。 功能特性 文件上传&#xff1a;支持普通文件上传和分片上传&#xff08;multipart upload&#xff09; 文件下载&#xff1a;通过 HTTP GET 请…

JBoltAI的AI应用中台:构建企业智能化的坚实基础

在当今数字化与智能化交织的时代&#xff0c;企业对于AI技术的需求日益增长&#xff0c;如何高效、稳定地集成AI能力成为企业转型的关键。JBoltAI的AI应用中台&#xff0c;作为企业智能化的重要基础设施&#xff0c;不仅为Java生态下的AI应用开发提供了强有力的支撑&#xff0c…

企业上云转型的 “压舱石”—— 云服务器如何破解中小微企业数字化痛点​

​在数字经济加速渗透的今天&#xff0c;中小微企业的数字化转型不再是 “选择题”&#xff0c;而是 “生存题”。但资金有限、技术人才匮乏、运维能力薄弱等现实困境&#xff0c;让众多企业在数字化门口望而却步。云服务器的出现&#xff0c;以 “按需付费、弹性伸缩、简化运维…

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

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

一键生成专业文献综述

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

数字经济的 “安全基石”—— 云服务器零信任架构如何筑牢数据安全防线​

数字化转型过程中&#xff0c;数据已成为企业核心资产&#xff0c;但云原生架构的普及使安全边界逐渐模糊&#xff0c;传统 “边界防护” 模式难以应对容器逃逸、API 漏洞、内部违规等新型安全威胁。基于零信任 “永不信任、始终验证” 核心理念的云服务器安全体系&#xff0c;…

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

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

基于多模型比较的慢性肾病分类模型设计与优化研究(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码

基于多模型比较的慢性肾病分类模型设计与优化研究(设计源文件万字报告讲解)&#xff08;支持资料、图片参考_相关定制&#xff09;_文章底部可以扫码 选用KNN、决策树、逻辑回归、SVM和AdaBoost五种算法进行全面评估」 机器学习、大数据分析原创报告 实交高分&#xff0c;欢迎询…

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必备!本科生毕业论文AI论文网站TOP9测评

2026必备&#xff01;本科生毕业论文AI论文网站TOP9测评 2026年本科生论文写作工具测评&#xff1a;为什么需要一份权威榜单&#xff1f; 随着人工智能技术的不断进步&#xff0c;越来越多的本科生开始借助AI论文网站提升写作效率、优化内容质量。然而&#xff0c;面对市场上琳…

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

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