0


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

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

通过this.getClass()方法获取

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

通过ClassPathResource获取

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

通过hutool工具类ResourceUtil获取

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

总结

不想折腾的同学可以直接用method3和method4的方法来使用,也可以将模板和资源文件外置,通过绝对路径获取对应文件。有好的方法也欢迎大家一起交流沟通~

代码

  1. import cn.hutool.core.io.FileUtil;
  2. import cn.hutool.core.io.resource.ClassPathResource;
  3. import cn.hutool.core.io.resource.ResourceUtil;
  4. import com.alibaba.excel.EasyExcel;
  5. import com.alibaba.excel.ExcelWriter;
  6. import com.alibaba.excel.enums.WriteDirectionEnum;
  7. import com.alibaba.excel.write.metadata.WriteSheet;
  8. import com.alibaba.excel.write.metadata.fill.FillConfig;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.BufferedReader;
  13. import java.io.IOException;
  14. import java.io.InputStream;
  15. import java.io.InputStreamReader;
  16. import java.io.UnsupportedEncodingException;
  17. import java.net.URLEncoder;
  18. import java.nio.charset.StandardCharsets;
  19. import java.util.List;
  20. @RestController
  21. @RequestMapping("/temp")
  22. public class TemplateController {
  23. /**
  24. * this.getClass()方法获取
  25. * @param response
  26. * @throws IOException
  27. */
  28. @RequestMapping("/method1")
  29. public void method1(HttpServletResponse response) throws IOException {
  30. System.out.println("----------method1 start");
  31. String filename = "template.xlsx";
  32. String bashPatch = this.getClass().getClassLoader().getResource("").getPath();
  33. System.out.println(bashPatch);
  34. String textFile = "template.txt";
  35. String textPath = this.getClass().getClassLoader().getResource("").getPath();
  36. List<String> dataList = FileUtil.readUtf8Lines(textPath + "/template/" + textFile);
  37. for (String data : dataList) {
  38. System.out.println(data);
  39. }
  40. try (ExcelWriter excelWriter =
  41. EasyExcel.write(response.getOutputStream())
  42. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  43. // .withTemplate(resource.getFile().getAbsolutePath())
  44. .withTemplate(bashPatch + "/template/" + filename)
  45. .build()
  46. ) {
  47. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  48. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  49. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  50. excelWriter.finish();
  51. }
  52. try {
  53. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  54. } catch (UnsupportedEncodingException e) {
  55. throw new RuntimeException(e);
  56. }
  57. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  58. }
  59. @RequestMapping("/method2")
  60. public void method2(HttpServletResponse response) throws IOException {
  61. System.out.println("----------method2 start");
  62. String filename = "template.xlsx";
  63. String bashPatch = this.getClass().getClassLoader().getResource("template").getPath();
  64. System.out.println(bashPatch);
  65. String textFile = "template.txt";
  66. String textPath = this.getClass().getClassLoader().getResource("template").getPath();
  67. List<String> dataList = FileUtil.readUtf8Lines(textPath + "/" + textFile);
  68. for (String data : dataList) {
  69. System.out.println(data);
  70. }
  71. try (ExcelWriter excelWriter =
  72. EasyExcel.write(response.getOutputStream())
  73. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  74. // .withTemplate(resource.getFile().getAbsolutePath())
  75. .withTemplate(bashPatch + "/" + filename)
  76. .build()
  77. ) {
  78. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  79. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  80. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  81. excelWriter.finish();
  82. }
  83. try {
  84. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  85. } catch (UnsupportedEncodingException e) {
  86. throw new RuntimeException(e);
  87. }
  88. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  89. }
  90. @RequestMapping("/method3")
  91. public void method3(HttpServletResponse response) throws IOException {
  92. System.out.println("----------method3 start");
  93. String filename = "template.xlsx";
  94. InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template" + "/" + filename);
  95. // System.out.println(inputStream);
  96. String textFile = "template.txt";
  97. InputStream textStream = this.getClass().getClassLoader().getResourceAsStream("template" + "/" + textFile);
  98. BufferedReader reader = new BufferedReader(new InputStreamReader(textStream));
  99. String line;
  100. try {
  101. while ((line = reader.readLine()) != null) {
  102. System.out.println(line);
  103. }
  104. } catch (IOException e) {
  105. e.printStackTrace(); // 异常处理
  106. }
  107. try (ExcelWriter excelWriter =
  108. EasyExcel.write(response.getOutputStream())
  109. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  110. // .withTemplate(resource.getFile().getAbsolutePath())
  111. .withTemplate(inputStream)
  112. .build()
  113. ) {
  114. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  115. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  116. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  117. excelWriter.finish();
  118. }
  119. try {
  120. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  121. } catch (UnsupportedEncodingException e) {
  122. throw new RuntimeException(e);
  123. }
  124. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  125. }
  126. @RequestMapping("/method4")
  127. public void method4(HttpServletResponse response) throws IOException {
  128. System.out.println("----------method4 start");
  129. String filename = "template.xlsx";
  130. InputStream inputStream = this.getClass().getResourceAsStream("/template" + "/" + filename);
  131. // System.out.println(inputStream);
  132. String textFile = "template.txt";
  133. InputStream textStream = this.getClass().getResourceAsStream("/template" + "/" + textFile);
  134. BufferedReader reader = new BufferedReader(new InputStreamReader(textStream));
  135. String line;
  136. try {
  137. while ((line = reader.readLine()) != null) {
  138. System.out.println(line);
  139. }
  140. } catch (IOException e) {
  141. e.printStackTrace(); // 异常处理
  142. }
  143. try (ExcelWriter excelWriter =
  144. EasyExcel.write(response.getOutputStream())
  145. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  146. // .withTemplate(resource.getFile().getAbsolutePath())
  147. .withTemplate(inputStream)
  148. .build()
  149. ) {
  150. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  151. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  152. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  153. excelWriter.finish();
  154. }
  155. try {
  156. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  157. } catch (UnsupportedEncodingException e) {
  158. throw new RuntimeException(e);
  159. }
  160. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  161. }
  162. /**
  163. * 通过ClassPathResource获取
  164. * @param response
  165. * @throws IOException
  166. */
  167. @RequestMapping("/method5")
  168. public void method5(HttpServletResponse response) throws IOException {
  169. System.out.println("----------method5 start");
  170. String filename = "template.xlsx";
  171. ClassPathResource classPathResource = new ClassPathResource("template" + "/" + filename);
  172. String textFile = "template.txt";
  173. ClassPathResource textResource = new ClassPathResource("template" + "/" + textFile);
  174. List<String> dataList = FileUtil.readUtf8Lines(textResource.getAbsolutePath());
  175. for (String data : dataList) {
  176. System.out.println(data);
  177. }
  178. try (ExcelWriter excelWriter =
  179. EasyExcel.write(response.getOutputStream())
  180. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  181. .withTemplate(classPathResource.getAbsolutePath())
  182. .build()
  183. ) {
  184. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  185. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  186. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  187. excelWriter.finish();
  188. }
  189. try {
  190. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  191. } catch (UnsupportedEncodingException e) {
  192. throw new RuntimeException(e);
  193. }
  194. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  195. }
  196. /**
  197. * 通过hutool工具类ResourceUtil获取
  198. * @param response
  199. * @throws IOException
  200. */
  201. @RequestMapping("/method6")
  202. public void method6(HttpServletResponse response) throws IOException {
  203. System.out.println("----------method6 start");
  204. String filename = "template.xlsx";
  205. String filePath = ResourceUtil.getResource("template" + "/" + filename).getPath();
  206. String textFile = "template.txt";
  207. String textPath = ResourceUtil.getResource("template" + "/" + textFile).getPath();
  208. List<String> dataList = FileUtil.readUtf8Lines(textPath);
  209. for (String data : dataList) {
  210. System.out.println(data);
  211. }
  212. try (ExcelWriter excelWriter =
  213. EasyExcel.write(response.getOutputStream())
  214. .autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
  215. .withTemplate(filePath)
  216. .build()
  217. ) {
  218. WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
  219. FillConfig userFillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  220. FillConfig titleFillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
  221. excelWriter.finish();
  222. }
  223. try {
  224. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
  225. } catch (UnsupportedEncodingException e) {
  226. throw new RuntimeException(e);
  227. }
  228. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  229. }
  230. }

pom依赖

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.8.9</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>easyexcel</artifactId>
  9. <version>3.3.3</version>
  10. </dependency>
标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/u010479989/article/details/141674584
版权归原作者 小灰灰__ 所有, 如有侵权,请联系我们删除。

“SpringBoot下获取resources目录下文件的常用方法”的评论:

还没有评论