解决java项目jar打包后读取文件失败的问题

java项目jar打包后读取文件失败 在本地项目读取文件时

this.getClass().getClassLoader().getResource("").getPath()+fileNamethis.getClass().getResource("/filename").getPath()

都是可以成功的
但是jar打包后上面方式读取文件时 会变成 jar!filename 这样的形式去读取文件,这样是读取不到文件的
可以使用
Test.class.getResourceAsStream("/filename")

读取文件 以流的形式读取文件 是可以读取的到的
这样就可以在打包后将文件进行读取
SpringBoot项目打包成jar后获取classpath下文件失败 公司的一个SpringBoot项目中,有需要下载文件模板的需求,按理来说分布式项目文件都应该上传到文件服务器,但是由于文件不是太多于是就放在了classpath下,在本地开发的时候发现都能正常下载文件,但是打包成jar上传到Linxu测试环境上就报错,找不到classpath路径。
原因
原因是项目打包后Spring试图访问文件系统路径,但无法访问JAR包中的路径。
我们使用ResourceUtils.getFile("classpath:"); 这样的方式是获取不到路径的。
解决方案
我们虽然不能直接获取文件资源路径,但是我们可以通过流的方式读取资源,拿到输入流过后我们就可以对其做操作了。
关键代码如下:
ClassPathResource resource = new ClassPathResource("\\static\\pattern\\test.txt"); // static/pattern下的 test.txt文件InputStream in = resource.getInputStream(); //获取文件输入流

示例Demo
1. 在static下新建pattern目录,并新建一个名为 test.txt的文件
解决java项目jar打包后读取文件失败的问题
文章图片

2. 新建DownloadController.java
代码如下:
package com.example.jekins.controller; import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; @RestControllerpublic class DownloadController {@GetMapping("/download/pattern")public void downloadPattern(HttpServletRequest request, HttpServletResponse response){System.out.println("开始下载文件....."); ClassPathResource resource = new ClassPathResource("\\static\\pattern\\test.txt"); try {//获取文件输入流InputStream in = resource.getInputStream(); //下载文件downFile("test文件.txt",request,response,in); } catch (IOException e) {e.printStackTrace(); }}/*** 下载文件* @param fileName 下载文件名称* @param response 响应* @throws IOException 异常*/public static void downFile(String fileName,HttpServletRequest request,HttpServletResponse response,InputStream in) throws IOException {//输出流自动关闭,java1.7新特性try(OutputStream os = response.getOutputStream()) {fileName = URLEncoder.encode(fileName, "UTF-8"); response.reset(); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType("application/octet-stream; charset=UTF-8"); byte[] b = new byte[in.available()]; in.read(b); os.write(b); os.flush(); } catch (Exception e) {System.out.println("fileName=" + fileName); e.printStackTrace(); } finally {if (in != null) {in.close(); }}}}

3. 测试
使用Maven工具把项目打成jar包
解决java项目jar打包后读取文件失败的问题
文章图片

在target下生成了jar包
解决java项目jar打包后读取文件失败的问题
文章图片

进入jar包所在的文件夹,按住shift并右击,点击在此处打开命令行窗口。输入命令启动项目 java -jar 打包后的文件
解决java项目jar打包后读取文件失败的问题
文章图片

我设置的端口是8086,浏览器地址栏输入http://127.0.0.1:8086/download/pattern
此时我们可以卡看到test.txt文件下载成功
解决java项目jar打包后读取文件失败的问题
文章图片

【解决java项目jar打包后读取文件失败的问题】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读