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

2024-08-29 13:20

本文主要是介绍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依赖

        <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>

这篇关于SpringBoot下获取resources目录下文件的常用方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1117978

相关文章

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使

Java Spring的依赖注入理解及@Autowired用法示例详解

《JavaSpring的依赖注入理解及@Autowired用法示例详解》文章介绍了Spring依赖注入(DI)的概念、三种实现方式(构造器、Setter、字段注入),区分了@Autowired(注入... 目录一、什么是依赖注入(DI)?1. 定义2. 举个例子二、依赖注入的几种方式1. 构造器注入(Con

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

如何在Java Spring实现异步执行(详细篇)

《如何在JavaSpring实现异步执行(详细篇)》Spring框架通过@Async、Executor等实现异步执行,提升系统性能与响应速度,支持自定义线程池管理并发,本文给大家介绍如何在Sprin... 目录前言1. 使用 @Async 实现异步执行1.1 启用异步执行支持1.2 创建异步方法1.3 调用

java内存泄漏排查过程及解决

《java内存泄漏排查过程及解决》公司某服务内存持续增长,疑似内存泄漏,未触发OOM,排查方法包括检查JVM配置、分析GC执行状态、导出堆内存快照并用IDEAProfiler工具定位大对象及代码... 目录内存泄漏内存问题排查1.查看JVM内存配置2.分析gc是否正常执行3.导出 dump 各种工具分析4.

Spring Boot配置和使用两个数据源的实现步骤

《SpringBoot配置和使用两个数据源的实现步骤》本文详解SpringBoot配置双数据源方法,包含配置文件设置、Bean创建、事务管理器配置及@Qualifier注解使用,强调主数据源标记、代... 目录Spring Boot配置和使用两个数据源技术背景实现步骤1. 配置数据源信息2. 创建数据源Be

Spring Boot 3.x 中 WebClient 示例详解析

《SpringBoot3.x中WebClient示例详解析》SpringBoot3.x中WebClient是响应式HTTP客户端,替代RestTemplate,支持异步非阻塞请求,涵盖GET... 目录Spring Boot 3.x 中 WebClient 全面详解及示例1. WebClient 简介2.

Java中使用 @Builder 注解的简单示例

《Java中使用@Builder注解的简单示例》@Builder简化构建但存在复杂性,需配合其他注解,导致可变性、抽象类型处理难题,链式编程非最佳实践,适合长期对象,避免与@Data混用,改用@G... 目录一、案例二、不足之处大多数同学使用 @Builder 无非就是为了链式编程,然而 @Builder

在IntelliJ IDEA中高效运行与调试Spring Boot项目的实战步骤

《在IntelliJIDEA中高效运行与调试SpringBoot项目的实战步骤》本章详解SpringBoot项目导入IntelliJIDEA的流程,教授运行与调试技巧,包括断点设置与变量查看,奠定... 目录引言:为良驹配上好鞍一、为何选择IntelliJ IDEA?二、实战:导入并运行你的第一个项目步骤1