欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot下獲取resources目錄下文件的常用方法

 更新時間:2024年10月30日 10:46:38   作者:常量俠  
本文詳細介紹了SpringBoot獲取resources目錄下文件的常用方法,包括使用this.getClass()方法、ClassPathResource獲取以及hutool工具類ResourceUtil獲取,感興趣的可以了解一下

今天給大家?guī)鞸pringBoot獲取resources目錄下文件的常用方法,示例中的方法是讀取resources目錄下的txt和xlsx文件,并將xlsx導出到excel的簡單寫法。完整代碼放在最后。

通過this.getClass()方法獲取

method1 - method4都是通過這個方法獲取文件的寫法,這四種寫法在idea中都可以正常運行,jar包執(zhí)行后method1和method2報錯,提示找不到文件,method3和method4可以正常運行

通過ClassPathResource獲取

method5是通過這種方法實現(xiàn),idea中可以正常運行,打包后的jar中提示找不到文件

通過hutool工具類ResourceUtil獲取

method6是通過這種方法實現(xiàn),和method情況一樣,同樣是idea中可以正常運行,導出的jar中提示找不到文件

總結(jié)

不想折騰的同學可以直接用method3和method4的方法來使用,也可以將模板和資源文件外置,通過絕對路徑獲取對應(yīng)文件。有好的方法也歡迎大家一起交流溝通~

代碼

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) // 不要自動關(guān)閉,交給 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) // 不要自動關(guān)閉,交給 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) // 不要自動關(guān)閉,交給 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) // 不要自動關(guān)閉,交給 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) // 不要自動關(guān)閉,交給 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) // 不要自動關(guān)閉,交給 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>

到此這篇關(guān)于SpringBoot下獲取resources目錄下文件的常用方法的文章就介紹到這了,更多相關(guān)SpringBoot獲取resources目錄下文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Springboot安全框架整合SpringSecurity實現(xiàn)方式

    Springboot安全框架整合SpringSecurity實現(xiàn)方式

    這篇文章主要介紹了Spring全家桶中Springboot安全框架整合SpringSecurity的實現(xiàn)方式,有需要的朋友可以借鑒參考下,希望可以有所幫助
    2021-09-09
  • java編程簡單獲取圖片像素的方法

    java編程簡單獲取圖片像素的方法

    這篇文章主要介紹了java編程簡單獲取圖片像素的方法,涉及Java針對圖片的讀取與屬性獲取技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-11-11
  • springboot配置nacos的實現(xiàn)示例

    springboot配置nacos的實現(xiàn)示例

    本文將介紹如何在Spring?Boot中配置Nacos,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-09-09
  • Springboot啟動原理詳細講解

    Springboot啟動原理詳細講解

    這篇文章主要介紹了SpringBoot啟動原理的分析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • 詳解使用Spring Boot開發(fā)Restful程序

    詳解使用Spring Boot開發(fā)Restful程序

    本篇文章主要介紹了詳解使用Spring Boot開發(fā)Restful程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • Java并發(fā)編程創(chuàng)建并運行線程的方法對比

    Java并發(fā)編程創(chuàng)建并運行線程的方法對比

    這篇文章主要為大家詳細介紹了Java并發(fā)編程創(chuàng)建并運行線程的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • java?IP歸屬地功能實現(xiàn)詳解

    java?IP歸屬地功能實現(xiàn)詳解

    前一陣子抖音和微博開始陸續(xù)上了IP歸屬地的功能,引起了眾多熱議,有大批在國外的老鐵們開始"原形畢露",被定位到國內(nèi)來,那么IP歸屬到底是怎么實現(xiàn)的呢?那么網(wǎng)紅們的歸屬地到底對不對呢
    2022-07-07
  • Java利用自定義注解實現(xiàn)數(shù)據(jù)校驗

    Java利用自定義注解實現(xiàn)數(shù)據(jù)校驗

    JSR303是一套JavaBean參數(shù)校驗的標準,它提供了一系列的校驗方式,這些校驗方式在javax.validation.constraints包中。本文就來聊聊如何利用它實現(xiàn)數(shù)據(jù)校驗
    2022-09-09
  • Java接口繼承和使用接口操作示例

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

    這篇文章主要介紹了Java接口繼承和使用接口操作,結(jié)合具體實例形式分析了Java接口繼承與使用的相關(guān)原理、操作技巧與注意事項,需要的朋友可以參考下
    2019-09-09
  • Spring中@Value注解的使用方法詳解

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

    這篇文章主要介紹了Spring中@Value注解的使用方法詳解,在spring項目中必不可少的就是讀取配置文件,那么讀取配置文件就有兩種方式,一種就是使用Spring中@Value注解,還有一種是使用SpringBoot中的@ConfigurationProperties注解,需要的朋友可以參考下
    2024-01-01

最新評論