springboot打包jar文件运行后无法读取jar目录中的Excel模板文件
·
原因:SpringBoot内嵌web容器,其特点是只有一个jar文件,在容器启动后不会解压缩。
解决方式:
1. 必须使用相对路径读取文件;
假设你的模板文件放在了 resources —> templates —> xlsx —> test.xlsx
2. 只能使用流去读取,不能用file;
// jar里面文件读取方式:
ClassPathResource classPathResource = new ClassPathResource("templates/xlsx/test.xlsx");
// 获取文件流
classPathResource .getInputStream();
如果要将流存储到数组中如下:
/**
* 输出流转字节数组
* @param input 输出流
* @return 字节数组
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int size = 0;
while (-1 != (size = input.read(buffer))) {
output.write(buffer, 0, size);
}
return output.toByteArray();
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)