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

相关文章

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.