最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

今天給大家?guī)?lái)SpringBoot獲取resources目錄下文件的常用方法,示例中的方法是讀取resources目錄下的txt和xlsx文件,并將xlsx導(dǎo)出到excel的簡(jiǎn)單寫(xiě)法。完整代碼放在最后。

通過(guò)this.getClass()方法獲取

method1 - method4都是通過(guò)這個(gè)方法獲取文件的寫(xiě)法,這四種寫(xiě)法在idea中都可以正常運(yùn)行,jar包執(zhí)行后method1和method2報(bào)錯(cuò),提示找不到文件,method3和method4可以正常運(yùn)行

通過(guò)ClassPathResource獲取

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

通過(guò)hutool工具類(lèi)ResourceUtil獲取

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

總結(jié)

不想折騰的同學(xué)可以直接用method3和method4的方法來(lái)使用,也可以將模板和資源文件外置,通過(guò)絕對(duì)路徑獲取對(duì)應(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) // 不要自動(dòng)關(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) // 不要自動(dòng)關(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) // 不要自動(dòng)關(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) // 不要自動(dòng)關(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");
    }


    /**
     * 通過(guò)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) // 不要自動(dòng)關(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");
    }

    /**
     * 通過(guò)hutool工具類(lèi)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) // 不要自動(dòng)關(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依賴(lài)

        <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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Spring 5.0集成log4j2日志管理的示例代碼

    Spring 5.0集成log4j2日志管理的示例代碼

    本篇文章主要介紹了Spring 5.0集成log4j2日志管理的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-12-12
  • Spring?Boot中使用Spring?MVC的示例解析

    Spring?Boot中使用Spring?MVC的示例解析

    MVC?是一種常見(jiàn)的軟件設(shè)計(jì)模式,用于分離應(yīng)用程序的不同部分以實(shí)現(xiàn)松散耦合和高內(nèi)聚性,這篇文章主要介紹了如何在Spring?Boot中使用Spring?MVC,需要的朋友可以參考下
    2023-04-04
  • JVM參數(shù)NativeMemoryTracking的使用

    JVM參數(shù)NativeMemoryTracking的使用

    本文主要介紹了JVM參數(shù)NativeMemoryTracking的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-01-01
  • JAVA實(shí)戰(zhàn)項(xiàng)目實(shí)現(xiàn)客戶選購(gòu)系統(tǒng)詳細(xì)流程

    JAVA實(shí)戰(zhàn)項(xiàng)目實(shí)現(xiàn)客戶選購(gòu)系統(tǒng)詳細(xì)流程

    讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的客戶選購(gòu)系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平
    2021-10-10
  • 客戶端設(shè)置超時(shí)時(shí)間真的很重要

    客戶端設(shè)置超時(shí)時(shí)間真的很重要

    今天小編就為大家分享一篇關(guān)于客戶端設(shè)置超時(shí)時(shí)間真的很重要,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-12-12
  • 詳解IDEA的快捷鍵及智能提示

    詳解IDEA的快捷鍵及智能提示

    這篇文章主要介紹了詳解IDEA的快捷鍵及智能提示,文中有非常詳細(xì)的快捷鍵及智能提示的說(shuō)明,對(duì)正在使用IDEA的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05
  • SpringBoot整合Liquibase實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)管理和遷移

    SpringBoot整合Liquibase實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)管理和遷移

    Liquibase是一個(gè)用于用于跟蹤、管理和應(yīng)用數(shù)據(jù)庫(kù)變化的開(kāi)源工具,通過(guò)日志文件(changelog)的形式記錄數(shù)據(jù)庫(kù)的變更(changeset),然后執(zhí)行日志文件中的修改,將數(shù)據(jù)庫(kù)更新或回滾(rollback)到一致的狀態(tài),本文主要介紹SpringBoot與Liquibase的集成,需要的朋友可以參考下
    2024-11-11
  • 如何優(yōu)雅的實(shí)現(xiàn)將Collection轉(zhuǎn)為Map

    如何優(yōu)雅的實(shí)現(xiàn)將Collection轉(zhuǎn)為Map

    這篇文章主要介紹了如何優(yōu)雅的實(shí)現(xiàn)將Collection轉(zhuǎn)為Map,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • Java后端接入微信小程序?qū)崿F(xiàn)登錄功能

    Java后端接入微信小程序?qū)崿F(xiàn)登錄功能

    這篇文章主要介紹了Java如何在后端接入微信小程序從而實(shí)現(xiàn)登錄功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下
    2023-06-06
  • SpringBoot中Redisson延遲隊(duì)列的示例

    SpringBoot中Redisson延遲隊(duì)列的示例

    延時(shí)隊(duì)列是一種常見(jiàn)的需求,延時(shí)隊(duì)列允許我們延遲處理某些任務(wù),本文主要介紹了Redisson延遲隊(duì)列的示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-06-06

最新評(píng)論

西乌珠穆沁旗| 原阳县| 娱乐| 衡东县| 迁安市| 昂仁县| 陵水| 城步| 景泰县| 景泰县| 会理县| 沈丘县| 昂仁县| 石林| 丹凤县| 濉溪县| 白沙| 浮梁县| 昌宁县| 庆安县| 收藏| 崇明县| 阿图什市| 揭阳市| 浮梁县| 五常市| 绥芬河市| 辽宁省| 勃利县| 恩平市| 上林县| 凤翔县| 余庆县| 紫云| 丹江口市| 林芝县| 兴业县| 西安市| 荣成市| 杨浦区| 永康市|