简体   繁体   中英

How to get a java/resources file to InputStream?

I have an excel file in src/main/resources (/resources/files/templates). I want to read it to 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.


If you are in a non-static method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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