开发者

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

开发者 https://www.devze.com 2024-10-31 10:20 出处:网络 作者: 常量侠
目录通过this.getClass()方法获取通过ClassPathResource获取通过hutool工具类ResourceUtil获取总结今天给大家带来SpringBoot获取resources目录下文件的常用方法,示例中的方法是读取resources目录下的txt和xlsx文件,
目录
  • 通过this.getClass()方法获取
  • 通过ClassPathResource获取
  • 通过hutool工具类ResourceUtil获取
  • 总结

今天给大家带来SpringBoot获取resources目录下文件的常用方法,示例中的方法是读取resources目录下的txt和xlsx文件,并将xlsx导出到excel的简单写法。完整代码放在最后。

通过this.getClass()方法获取

method1 - method4都是通过这个方法获取文件的写法,这四种写法在idea中都可以正常运行,jar包执行后method1和method2报错,提示找不到文件,method3和method4可以正常运行

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

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

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

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

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

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

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

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

通过ClassPathResource获取

method5是通过这种方法实现,idea中可以正常运行,打包后的jar中提示找不到文件

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

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

通过hutool工具类ResourceUtil获取

method6是通过这种方法实现,和method情况一样,同样是idea中可以正常运行,导出的jar中提示找不到文件

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

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

总结

不想折腾的同学可以直接用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 {
           www.devze.com 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())
                             .autoC编程客栈loseStream(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())
   python                          .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);
        }
        responsezwuuAjOIpn.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目录下文件内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)! 

0

精彩评论

暂无评论...
验证码 换一张
取 消