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>
相关推荐
mjhcsp12 小时前
C++ Manacher 算法:原理、实现与应用全解析
java·c++·算法·manacher 算法
Coder_Boy_12 小时前
基于SpringAI的在线考试系统-企业级软件研发工程应用规范案例
java·运维·spring boot·软件工程·devops
indexsunny12 小时前
互联网大厂Java面试实战:微服务、Spring Boot与Kafka在电商场景中的应用
java·spring boot·微服务·面试·kafka·电商
SUDO-112 小时前
Spring Boot + Vue 2 的企业级 SaaS 多租户招聘管理系统
java·spring boot·求职招聘·sass
sheji341612 小时前
【开题答辩全过程】以 基于spring boot的停车管理系统为例,包含答辩的问题和答案
java·spring boot·后端
重生之后端学习12 小时前
21. 合并两个有序链表
java·算法·leetcode·链表·职场和发展
源代码•宸12 小时前
Leetcode—1266. 访问所有点的最小时间【简单】
开发语言·后端·算法·leetcode·职场和发展·golang
南屿欣风12 小时前
Sentinel 熔断规则 - 异常比例(order & product 示例)笔记
java·开发语言
u01040583612 小时前
使用Java实现高性能的异步编程:CompletableFuture与Reactive Streams
java·开发语言
专注VB编程开发20年12 小时前
c#Type数组转成字符串的名称
java·开发语言