VS的FileInputStream VS使用ClassPathResource和的getResourceAsStream诚信档案 [英] FileInputStream vs ClassPathResource vs getResourceAsStream and file integrity

查看:737
本文介绍了VS的FileInputStream VS使用ClassPathResource和的getResourceAsStream诚信档案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题:

在钢骨混凝土/主/资源,我有一个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);

我得到这个错误:

I get this error :

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");

它的工作原理!

什么是错的?我不能硬code中的完整路径的文件。

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.

这code从源代码加载该文件,未经过滤

This code load the file from source, unfiltered

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

这code加载从目标目录中的文件,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

这篇关于VS的FileInputStream VS使用ClassPathResource和的getResourceAsStream诚信档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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