问题描述:最近打包项目发现,本地正常执行的代码,打成jar包执行会出现文件读取失败的问题。
package com.liu.springboot.controller; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.*; /** *将static中的favicon.ico 复制到D盘 * */ @Controller public class TestFile { @RequestMapping("/getFile") @ResponseBody public String read() { ClassPathResource classPathResource = new ClassPathResource("static/favicon.ico"); File copy = new File("D://copy.ico"); OutputStream outputStream = null; InputStream inputStream = null; int len; byte[] buf = new byte[100]; try { outputStream = new FileOutputStream(copy); File file = classPathResource.getFile(); inputStream = new FileInputStream(file); while ((len = inputStream.read(buf))>0) { outputStream.write(buf,0,len); } // System.out.println("ok"); return "ok"; }catch (IOException io) { return "false"; } finally { try { outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
在idea中执行是ok的
可是打包后就会出现异常
发现这行代码出现问题,报了空指针
File file = classPathResource.getFile();
解决办法:
outputStream = new FileOutputStream(copy); //File file = classPathResource.getFile(); //inputStream = new FileInputStream(file); //直接得到输入流 inputStream = classPathResource.getInputStream(); while ((len = inputStream.read(buf))>0) { outputStream.write(buf,0,len); }
这样就可以了,其实发现完全没必要使用classPathResource.getFile(),直接 classPathResource.getInputStream();就行了。
如果你在某种情况下实在需要以File形式,那么你可以将从 classPathResource.getInputStream();获得的流里的内容,复制一份到文件中,也就是上文做的工作·,然后再操作(读)这个文件的拷贝文件。
暂时记录下,以后再详细查找原因