springboot读取本地项目文件

在读取springBoot+gradle构建的项目时,如果使用传统的FileInputStream读取文件流或者ResourceUtils工具类的方式

File file= ResourceUtils.getFile("classpath:test.txt");

在springboot中可以使用ClassPathResource获取文件流的方式方便下载文件

try {
    ClassPathResource classPathResource = new ClassPathResource("sql/SCHEDULE_TASK.sql");
File file = classPathResource.getFile();
InputStream inputStream = classPathResource.getInputStream();
  //输出文件
InputStream fis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();

//获取文件的名字再浏览器下载页面
String name = file.getName();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream out = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
out.write(buffer);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
最后就是浏览器访问接口下载文件了

 

这样下载文件就很简单了

 

 



posted @ 2019-06-28 17:14  执着的你  阅读(24543)  评论(2编辑  收藏  举报