简体   繁体   English

如何将Java /资源文件获取到InputStream?

[英]How to get a java/resources file to InputStream?

I have an excel file in src/main/resources (/resources/files/templates). 我在src / main / resources(/ resources / files / templates)中有一个Excel文件。 I want to read it to InputStream. 我想将其读取到InputStream。 I am not finding the right syntax for this. 我没有为此找到合适的语法。

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";

    try {
        InputStream inputStream = new URL("file:///"  + fn).openStream();

Above is not working. 上面不起作用。 I think the path is wrong. 我认为路径是错误的。 How to give correct path for files stored in resources? 如何为资源中存储的文件提供正确的路径?

这对我有用。

InputStream is = YourClass.class.getClassLoader().getResourceAsStream("relative path to your file starting from resources folder");

If you are in any method (static or non-static): 如果采用任何方法(静态或非静态):

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
InputStream in = Clazz.class.getResourceAsStream(fn);

Where Clazz is the name of the class you are in. Clazz是您所在班级的名称。


If you are in a non-static method: 如果您使用的是非静态方法:

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
InputStream in = getClass().getResourceAsStream(fn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM