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

 更新时间:2024年10月30日 10:46:38   作者:常量侠  
本文详细介绍了SpringBoot获取resources目录下文件的常用方法,包括使用this.getClass()方法、ClassPathResource获取以及hutool工具类ResourceUtil获取,感兴趣的可以了解一下

今天给大家带来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目录下文件的常用方法的文章就介绍到这了,更多相关SpringBoot获取resources目录下文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • Springboot安全框架整合SpringSecurity实现方式

    Springboot安全框架整合SpringSecurity实现方式

    这篇文章主要介绍了Spring全家桶中Springboot安全框架整合SpringSecurity的实现方式,有需要的朋友可以借鉴参考下,希望可以有所帮助
    2021-09-09
  • java编程简单获取图片像素的方法

    java编程简单获取图片像素的方法

    这篇文章主要介绍了java编程简单获取图片像素的方法,涉及Java针对图片的读取与属性获取技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-11-11
  • springboot配置nacos的实现示例

    springboot配置nacos的实现示例

    本文将介绍如何在Spring Boot中配置Nacos,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-09-09
  • Springboot启动原理详细讲解

    Springboot启动原理详细讲解

    这篇文章主要介绍了SpringBoot启动原理的分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 详解使用Spring Boot开发Restful程序

    详解使用Spring Boot开发Restful程序

    本篇文章主要介绍了详解使用Spring Boot开发Restful程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • Java并发编程创建并运行线程的方法对比

    Java并发编程创建并运行线程的方法对比

    这篇文章主要为大家详细介绍了Java并发编程创建并运行线程的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • java IP归属地功能实现详解

    java IP归属地功能实现详解

    前一阵子抖音和微博开始陆续上了IP归属地的功能,引起了众多热议,有大批在国外的老铁们开始"原形毕露",被定位到国内来,那么IP归属到底是怎么实现的呢?那么网红们的归属地到底对不对呢
    2022-07-07
  • Java利用自定义注解实现数据校验

    Java利用自定义注解实现数据校验

    JSR303是一套JavaBean参数校验的标准,它提供了一系列的校验方式,这些校验方式在javax.validation.constraints包中。本文就来聊聊如何利用它实现数据校验
    2022-09-09
  • Java接口继承和使用接口操作示例

    Java接口继承和使用接口操作示例

    这篇文章主要介绍了Java接口继承和使用接口操作,结合具体实例形式分析了Java接口继承与使用的相关原理、操作技巧与注意事项,需要的朋友可以参考下
    2019-09-09
  • Spring中@Value注解的使用方法详解

    Spring中@Value注解的使用方法详解

    这篇文章主要介绍了Spring中@Value注解的使用方法详解,在spring项目中必不可少的就是读取配置文件,那么读取配置文件就有两种方式,一种就是使用Spring中@Value注解,还有一种是使用SpringBoot中的@ConfigurationProperties注解,需要的朋友可以参考下
    2024-01-01

最新评论