11月30

springboot打包jar文件运行后无法读取jar目录中的Excel文件

| |
22:28编程杂谈  From: 本站原创
原因:SpringBoot内嵌web容器,其特点是只有一个jar文件,在容器启动后不会解压缩。

解决方式:

1. 必须使用相对路径读取文件;

假设你的模板文件放在了 resources —> templates —> test.xlsx

2. 只能使用流去读取,不能用file;

  // jar里面文件读取方式:
  ClassPathResource classPathResource = new ClassPathResource("templates/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();
    }


来源:Heck's Blog
地址:https://www.heckjj.com/post/626/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!
阅读(316) | 评论(0) | 引用(0)