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

相关文章

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin