近些时日,整理一些旧项目,发现了一些头疼的问题:之前打成war包后在tomcat中运行时能读取到的文件,现在改架构打成jar包后反而读取不了了,我看了下异常是很常见的“FileNotFoundException”异常。我解压了jar包后,发现其读取地址是对的,不明所以,又换了几种常规方法发现通过流的方式是能够获取的。
/**
* 文件读取处理---静态文件处理
*/
@GetMapping("/getTempFile")
public void getTempFile(HttpServletResponse response) throws IOException {
//设置下载文件的名称
String fileName = "test.txt";
//设置下载
response.setHeader("content-disposition", "attachment;filename=" + fileName);
response.setContentType("content-type:octet-stream");
//获取项目的地址,用于存放需要执行的其他插件比如dll、exe,
// String projectPath = SystemUtils.USER_DIR;
String tempFile = "static/temp/test.txt";
//getResourceAsStream:获取resource文件下文件,按流的方式可以在jar包中读取而不会出现 FileNotFoundException
InputStream in = this.getClass().getClassLoader().getResourceAsStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
//数据流copy,--commons-fileupload.jar
Streams.copy(in, bos, true);
in.close();
}
我本地的文件是这样的,