springboot读取本地项目文件

àì夳堔傛蜴生んèń 2021-11-14 13:32 680阅读 0赞

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

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

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

  1. try {
  2. ClassPathResource classPathResource = new ClassPathResource("sql/SCHEDULE_TASK.sql");
  3. File file = classPathResource.getFile();
  4. InputStream inputStream = classPathResource.getInputStream();
  5.   //输出文件
  6. InputStream fis = new BufferedInputStream(inputStream);
  7. byte[] buffer = new byte[fis.available()];
  8. fis.read(buffer);
  9. fis.close();
  10. response.reset();
  11. //获取文件的名字再浏览器下载页面
  12. String name = file.getName();
  13. response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
  14. response.addHeader("Content-Length", "" + file.length());
  15. OutputStream out = new BufferedOutputStream(response.getOutputStream());
  16. response.setContentType("application/octet-stream");
  17. out.write(buffer);
  18. out.flush();
  19. out.close();
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }
  23. 最后就是浏览器访问接口下载文件了

1718157-20190628170928112-2115120928.png

1718157-20190628171000092-110991161.png

这样下载文件就很简单了

转载于:https://www.cnblogs.com/lxp-java/p/11103803.html

发表评论

表情:
评论列表 (有 0 条评论,680人围观)

还没有评论,来说两句吧...

相关阅读

    相关 py读取本地文件

    在Python中,可以使用内置的`open()`函数来读取本地文件。以下是一个基本的示例,演示如何打开并读取一个文本文件: 使用 'r' 参数表示我们想要读取文件