FileInputStream vs ClassPathResource vs getResourceAsStream 和文件完整性 [英] FileInputStream vs ClassPathResource vs getResourceAsStream and file integrity

查看:29
本文介绍了FileInputStream vs ClassPathResource vs getResourceAsStream 和文件完整性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题:

在 src/main/resources 我有一个template.xlsx"文件.

in src/main/resources i have a "template.xlsx" file.

如果我这样做:

InputStream is = new ClassPathResource("template.xlsx").getInputStream();

或者这个:

InputStream is = ClassLoader.getSystemResourceAsStream("template.xlsx");

或者这个:

InputStream is = getClass().getResourceAsStream("/template.xlsx");

当我尝试创建工作簿时:

When i try to create a workbook :

Workbook wb = new XSSFWorkbook(is);

我收到此错误:

java.util.zip.ZipException: invalid block type

但是,当我得到这样的文件时:

BUT, when i get my file like this :

InputStream is = new FileInputStream("C:/.../src/main/resources/template.xlsx");

有效!

怎么了?我无法对文件的完整路径进行硬编码.

What is wrong ? I can't hardcode the fullpath to the file.

有人可以帮我吗?

谢谢

推荐答案

我遇到了同样的问题,您可能遇到了 maven 过滤的问题.

I had the same issue, you probably have a problem with maven filtering.

此代码从源加载文件,未过滤

This code load the file from source, unfiltered

InputStream is = new FileInputStream("C:/.../src/main/resources/template.xlsx");

此代码从目标目录加载文件,在 maven 过滤内容后

This code load the file from the target directory, after maven has filtered the content

InputStream is = getClass().getResourceAsStream("/template.xlsx");

你不应该像 excel 那样过滤二进制文件并使用两个互斥的资源集,如本页底部所述 maven 资源插件

You should not filter binary files like excel and use two mutually exclusive resource sets as described at the bottom of this page maven resources plugin

这篇关于FileInputStream vs ClassPathResource vs getResourceAsStream 和文件完整性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆