解决在spring boot打成jar包后读取resource下资源文件抛出 java.io.FileNotFoundException
具体报错如下:file:/data/XXX/xxxx.jar.!/BOOT-INF/classes!/configs/xxxxx.xlsx(No such file or directory),
开发环境spring boot2.15
需求:在resource下需要提供一套excel,world格式供前端下载模板
String file = "static/人员基础信息导入模板.xlsx"; BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); OutputStream outputStream = response.getOutputStream();这种读取方式只能在本地运行项目的时候使用,一旦发布项目(打包成jar)在调用这个接口时候会出现file:/data/XXX/xxxx.jar.!/BOOT-INF/classes!/configs/xxxxx.xlsx(No such file or directory);异常
完整代码可以直接使用
@GetMapping("/personnel/downloadTemplate") public void downloadLocal(HttpServletResponse response) throws IOException { /** 获取静态文件的路径 */ String path = "static/人员基础信息导入模板.xlsx"; /** 获取文件的名称 . 用来进行编码*/ String fileName = "人员基础信息导入模板.xlsx"; /** 将文件名称进行编码 */ response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("content-type:octet-stream"); /* .getClassLoader() 方法是在静态文件路径添加一个/ */ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path); OutputStream outputStream = response.getOutputStream(); try { byte[] buffer = new byte[1024]; int len; assert inputStream != null; while ((len = inputStream.read(buffer)) != -1) { /** 将流中内容写出去 .*/ outputStream.write(buffer, 0, len); } }catch (IOException e){ e.printStackTrace(); }finally { assert inputStream != null; inputStream.close(); outputStream.close(); } }如还有问题可以评论留言!
如果解决了你的问题,请右上角给点个赞。