SpringBoot下獲取resources目錄下文件的常用方法
今天給大家?guī)鞸pringBoot獲取resources目錄下文件的常用方法,示例中的方法是讀取resources目錄下的txt和xlsx文件,并將xlsx導(dǎo)出到excel的簡(jiǎn)單寫法。完整代碼放在最后。
通過this.getClass()方法獲取
method1 - method4都是通過這個(gè)方法獲取文件的寫法,這四種寫法在idea中都可以正常運(yùn)行,jar包執(zhí)行后method1和method2報(bào)錯(cuò),提示找不到文件,method3和method4可以正常運(yùn)行








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


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


總結(jié)
不想折騰的同學(xué)可以直接用method3和method4的方法來使用,也可以將模板和資源文件外置,通過絕對(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");
}
/**
* 通過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");
}
/**
* 通過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) // 不要自動(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依賴
<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)文章
JVM參數(shù)NativeMemoryTracking的使用
本文主要介紹了JVM參數(shù)NativeMemoryTracking的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
JAVA實(shí)戰(zhàn)項(xiàng)目實(shí)現(xiàn)客戶選購(gòu)系統(tǒng)詳細(xì)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的客戶選購(gòu)系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2021-10-10
SpringBoot整合Liquibase實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)管理和遷移
Liquibase是一個(gè)用于用于跟蹤、管理和應(yīng)用數(shù)據(jù)庫(kù)變化的開源工具,通過日志文件(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,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03
SpringBoot中Redisson延遲隊(duì)列的示例
延時(shí)隊(duì)列是一種常見的需求,延時(shí)隊(duì)列允許我們延遲處理某些任務(wù),本文主要介紹了Redisson延遲隊(duì)列的示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-06-06

