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

server/2024/10/11 13:28:49/

哈喽,大家好,今天给大家带来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依赖

        <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.9</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.3</version></dependency>


http://www.ppmy.cn/server/107665.html

相关文章

Verilog刷题笔记60

题目&#xff1a; Exams/2013 q2bfsm Consider a finite state machine that is used to control some type of motor. The FSM has inputs x and y, which come from the motor, and produces outputs f and g, which control the motor. There is also a clock input called …

【YOLOv8改进[Conv]】 感受野注意力卷积RFAConv(2024.3)| 使用RFAConv改进C2f + 含全部代码和详细修改方式

本文将进行在YOLOv8中使用 感受野注意力卷积RFAConv改进C2f 的实践,助力YOLOv8目标检测效果,文中含全部代码、详细修改方式。助您轻松理解改进的方法。

C++练习题:进阶算法——二分查找

第一部分&#xff1a;考点与作答区 考点&#xff1a; 查找算法的概念二分查找的原理二分查找的实现 作答区&#xff1a; 编写一个C程序&#xff0c;完成以下要求&#xff1a; 使用二分查找算法在一个整型数组中查找一个元素。打印查找结果。 请在下方空白处编写代码&#…

景芯SoC A72实战反馈

先说结论&#xff1a; 内容非常全面&#xff0c;讲解到位&#xff0c;会有专门的工程师一对一答疑&#xff0c;整个项目跑下来提升非常大&#xff0c;绝对物超所值&#xff01; 一些细节&#xff1a; 本人微电子专业研一在读&#xff0c;有过两次简单的数字芯片流片经历&…

Systemc example based on VCS

README VCS example path: $VCS_HOME/doc/examples/systemc/ SYSTEMC_HOME: module load systemc(or 自己download systemc, VCS_HOME下应该也有&#xff1a;$VCS_HOME/include/systemc233/tlm_utils) gcc需要是7.3.0版本&#xff0c;module load gcc/7.3.0 注意事项 vcs …

MYSQL:简述对B树和B+树的认识

MySQL的索引使用B树结构。 1、B树 在说B树之前&#xff0c;先说说B树&#xff0c;B树是一个多路平衡查找树&#xff0c;相较于普通的二叉树&#xff0c;不会发生极度不平衡的状况&#xff0c;同时也是多路的。 B树的特点是&#xff1a;他会将数据也保存在非叶子节点。而这个…

AI智能大数据分析足球AIAutoPrediction,提高足球比赛预测准确度的新方法

本文摘要&#xff1a;一、I智能大数据分析足球的原理I智能大数据分析足球的原理是利用机器学习和大数据分析技术&#xff0c;对足球比赛的各种数据进行分析和预测。这些数据包括球队历史成绩、球员数据、场地... 一、I智能大数据分析足球的原理 I智能大数据分析足球的原理是利…

基于yolov8的火焰烟雾检测系统python源码+onnx模型+评估指标曲线+精美GUI界面

【算法介绍】 基于YOLOv8的火焰烟雾检测系统是一款高效、实时的智能安全监控解决方案。该系统利用YOLOv8这一先进的深度学习模型&#xff0c;以其卓越的速度和准确性&#xff0c;能够在复杂环境中快速定位并分类火焰与烟雾&#xff0c;即使是微小的火源或稀薄的烟雾也能被精准…