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

news2024/9/23 1:40:27

哈喽,大家好,今天给大家带来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.coloradmin.cn/o/2084898.html

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

相关文章

linux安装mysql数据库,含公网链接(有网络带网安装)

1.检查是否存在mysql mysql出现这个&#xff0c;代表没安装 -bash: mysql: command not found 2.检查是否有mariadb数据库&#xff0c;如果有&#xff0c;需要先卸载。 rpm -qa | grep mariadb3.卸载现有的数据库 rpm -e --上个命令显示的名字4.在线安装&#xff0c;需要外…

【多线程】线程的等待通知机制-wait与notify

&#x1f490;个人主页&#xff1a;初晴~ &#x1f4da;相关专栏&#xff1a;多线程 / javaEE初阶 我们都知道&#xff0c;线程在系统调度上是随机的&#xff0c;因此线程之间执⾏的先后顺序难以预知。但在实际开发中有时我们希望控制多个线程执行某个逻辑的先后顺序&#xff…

基于JSP高校应届生就业信息管理系统的设计与实现(全网第一无二,阿龙原创设计)

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

C#骑砍逻辑类Mod制作详细解说

前言&#xff1a; 最近在研究骑砍的mod&#xff0c;主要是想修改其中的逻辑部分&#xff0c;因此有了这篇帖子。 一&#xff0c;文件夹与XML配置 在Modules创建一个新文件夹&#xff0c;文件夹名称随意&#xff0c;不影响实际的读取。 文件夹下面的位置需要固定&#xff0c;因…

大模型学习路线:从新手到专家的全面指南,从零基础到精通,非常详细收藏我这一篇就够了

随着人工智能技术的飞速发展&#xff0c;特别是近年来深度学习领域的突破&#xff0c;大规模预训练模型&#xff08;通常称为“大模型”&#xff09;已成为推动自然语言处理&#xff08;NLP&#xff09;、计算机视觉&#xff08;CV&#xff09;等领域发展的关键力量。本文将为你…

CSS 嵌套元素的隐藏规则

简单介绍一下&#xff0c;在 HTML 和 CSS 中&#xff0c;元素大体分为 块级元素、内联元素&#xff08;行内元素&#xff09;、块级内联元素&#xff08;行内块元素&#xff09;。它们有着不同的嵌套规则和特殊之处。 1. 行内元素 行内元素特点&#xff1a;不独占一行、不可设…

06- Python的标识符

Python 标识符的知识点 简单地理解&#xff0c;标识符就是一个名字&#xff0c;就好像我们每个人都有属于自己的名字&#xff0c;它的主要作用就是作为变量、函数、类、模块以及其他对象的名称。 Python 中标识符的命名不是随意的&#xff0c;而是要遵守一定的命令规则&#xf…

Qt 调用MFC dll,动态库中有界面

一、创建MFC 动态库工程 下一步 创建 点击确定 二、创建接口 这个是系统创建的&#xff0c;改成自己的接口。 头文件&#xff1a; #ifndef __WEB_ENGINE__ #define __WEB_ENGINE__#ifdef __cplusplus extern "C" { #endif__declspec(dllexport) bool __stdcall Loa…

Datawhale AI 夏令营-CV竞赛-Task2

# Datawhale AI 夏令营 夏令营手册&#xff1a;从零上手CV竞赛 比赛&#xff1a;2024“大运河杯”数据开发应用创新大赛——城市治理赛道 代码运行平台&#xff1a;厚德云 赛题任务 本赛题的任务是开发智能识别系统&#xff0c;用于自动检测和分类城市管理中的违规行为。通…

Vue组件的好处和理解、基本使用、注意事项、组件嵌套、VueComponent理解和原型链

目录 1. 组件的好处和理解2. Vue组件的使用2.1 Vue中使用组件的三大步骤2.2 注意事项 4. 组件的嵌套5. VueComponent的理解6. VueComponent原型链 1. 组件的好处和理解 传统方式编写应用&#xff0c;存在2大问题&#xff1a; 依赖关系混乱&#xff0c;不好维护代码复用率不高…

中资优配:人气牛股10连板!

三大股指今日弱势轰动&#xff0c;均创2月初以来新低&#xff1b;小盘股较为生动&#xff0c;万得微盘股指数涨超1%&#xff1b;两市成交额再度萎缩至5000亿元下方&#xff1b;港股走势疲弱&#xff0c;两大股指均跌超1%。 具体来看&#xff0c;沪指在银行、酿酒等板块的拖累下…

ESP32-IDF http请求崩溃问题解决

文章目录 esp32s3 http请求崩溃问题代码讨论修正后不崩溃的代码 ESP32S3板子, 一运行http请求百度网站的例子, 就会panic死机, 记录下过程. esp32s3 http请求崩溃 一执行http请求的perform就会崩溃, 打印如图 ESP32-IDF 的http请求代码是根据官方demo来改的, 第一步先连接wi…

佰朔资本:大盘股和小盘股的区别?大中小盘股划分标准?

一般来说&#xff0c;大盘股&#xff1a;流通市值在500亿及以上&#xff0c;中盘股&#xff1a;流通市值在100亿~500亿之间&#xff0c;小盘股&#xff1a;流通市值在100亿及以下。 留意&#xff1a;流通市值是可以上市买卖流通的股数与股价乘积&#xff0c;总市值由流通市值与…

【项目源码】终于有人将打字游戏和编程英语结合起来啦!Java初学者的福音

Hello&#xff01;各位彦祖&#xff0c;亦菲们&#xff01;又是美好的一天&#xff01;今天给大家分享一个Java项目源码&#xff1a;Java打字游戏项目源码&#xff01; 看到这里&#xff0c;你可能会说&#xff01; 一个破打字游戏有什么可神气的&#xff01;&#xff01;&…

OpenCV 图像处理中滤波技术介绍

VS2022配置OpenCV环境 关于OpenCV在VS2022上配置的教程可以参考&#xff1a;VS2022 配置OpenCV开发环境详细教程 图像处理中滤波技术 图像滤波是图像处理中的一种重要技术&#xff0c;用于改善图像质量或提取图像中的特定特征。以下是一些常见的图像滤波技术&#xff1a; 均…

LeetCode 热题100-41 二叉树的层序遍历

二叉树的层序遍历 给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;[[3],[9,20],[15,7]]示例 2&…

线上预订酒店订房小程序源码系统 多商家入驻 带完整的安装代码包以及搭建部署教程

系统概述 线上预订酒店订房小程序源码系统是一款基于微信小程序开发的酒店预订系统。它充分利用了微信小程序的便捷性和普及性&#xff0c;为用户提供了一个方便、快捷的酒店预订渠道。同时&#xff0c;该系统还支持多商家入驻&#xff0c;允许不同的酒店商家在同一个平台上展…

uniapp自定义头部导航栏布局(普通版)

H5与微信小程序 通过获取系统信息和获取胶囊按钮的信息&#xff0c;得到获取标题栏高度&#xff0c;成而做好自定义头部导航栏 在微信小程序可使用 但在H5就保错&#xff0c;就需要优化 <!-- 全局custom-nav-bar组件 --> <template><view class"customN…

【Docker】Dockerfile实列-Nginx镜像构建

一、镜像构建步骤 实验准备&#xff1a;导入centos7镜像&#xff08;因为现在docker镜像拉取不下了&#xff09; docker load -i centos-7.tar.gz 1、建立构建目录&#xff0c;编写构建文件 [rootdocker-node1 ~]# mdkir /docker [rootdocker-node1 ~]# cd /docker [rootdo…

发现一个程序员最强外设,助你高效开发早日摸鱼!

简介 最近公司的副屏有点问题&#xff0c;经常屏闪&#xff0c;无意中和媳妇儿吐槽了几句。没想到&#xff0c;生日的时候&#xff0c;居然收到了她的礼物&#xff1a; 看到「程序员专用」的时候&#xff0c;我很开心的对媳妇儿表示了感谢&#xff0c;但内心第一反应是&#x…