admin 管理员组文章数量: 1184232
一,注意JAVA自动适配Linux与Windows文件路径分隔符
linux文件路径分隔符为 / ,windows的文件路径分隔符为 \ ,在开发项目过程中不确定用户使用何种操作系统,就需要自动适配路径。
目前已知java提供两种方法获取文件路径分割符:
public static final String FILE_SEPARATOR = File.separator;
//public static final String FILE_SEPARATOR = System.getProperty("file.separator");
二,Resource目录下文件读取
项目中涉及到Excle的导入功能,通常是我们定义完模板供用户下载,用户按照模板填写完后上传;这里待下载模板位置为resource/excelTemplate/test.xlsx,下方尝试了四种读取方式,并且测试了四种读取方式分别的windows开发环境下(IDE中)读取和生产环境(linux下jar包运行读取)。
第一种:本人采取的方式
ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
InputStream inputStream =classPathResource.getInputStream();
// 获取文件
File file = classPathResource.getFile();
// 获取文件路径
sourceFile = file.getPath();
第二种:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");
第三种:
InputStream inputStream = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");
第四种: Linux生产环境读取失败
File file = ResourceUtils.getFile("classpath:excleTemplate/test.xlsx");
InputStream inputStream = new FileInputStream(file);
经测试:
前三种方法在开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到
第四种只有开发环境 时可以读取到,生产环境读取失败。tomcat 解压后文件位置问题
三,下载
在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();
}
最后就是浏览器访问接口下载文件了
这样下载文件就很简单了
版权声明:本文标题:SpringBoot项目中Resource目录下文件下载及读取的几种方式 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1754290869a2985027.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论