SpringBoot下獲取resources目錄下文件的常用方法
今天給大家?guī)鞸pringBoot獲取resources目錄下文件的常用方法,示例中的方法是讀取resources目錄下的txt和xlsx文件,并將xlsx導(dǎo)出到excel的簡單寫法。完整代碼放在最后。
通過this.getClass()方法獲取
method1 - method4都是通過這個(gè)方法獲取文件的寫法,這四種寫法在idea中都可以正常運(yùn)行,jar包執(zhí)行后method1和method2報(bào)錯,提示找不到文件,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的方法來使用,也可以將模板和資源文件外置,通過絕對路徑獲取對應(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實(shí)現(xiàn)方式
這篇文章主要介紹了Spring全家桶中Springboot安全框架整合SpringSecurity的實(shí)現(xiàn)方式,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
springboot配置nacos的實(shí)現(xiàn)示例
本文將介紹如何在Spring?Boot中配置Nacos,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09
詳解使用Spring Boot開發(fā)Restful程序
本篇文章主要介紹了詳解使用Spring Boot開發(fā)Restful程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
Java并發(fā)編程創(chuàng)建并運(yùn)行線程的方法對比
這篇文章主要為大家詳細(xì)介紹了Java并發(fā)編程創(chuàng)建并運(yùn)行線程的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
Java利用自定義注解實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)
JSR303是一套JavaBean參數(shù)校驗(yàn)的標(biāo)準(zhǔn),它提供了一系列的校驗(yàn)方式,這些校驗(yàn)方式在javax.validation.constraints包中。本文就來聊聊如何利用它實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)2022-09-09

