0
点赞
收藏
分享

微信扫一扫

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();
    }


举报

相关推荐

0 条评论