简体   繁体   中英

Java - classLoader - reading files in a jar

I have a project made in Intelij where I have a function which reads some data from a file using :

InputStream stream = getClass().getClassLoader().getResourceAsStream(excelFilePath); 

and it works fine.

Now, I want to make a jar with the project + files and call that function from another project. The files are added to the jar , but when calling the function i get a null pointer exception, the stream is null ;

The file path is something like "exel\\\\filename" and it's on res/exel folder, where res is marked as a resource folder.

What am I doing wrong ?

I found the solution.

I had to replace

InputStream stream = getClass().getClassLoader().getResourceAsStream(excelFilePath);

with

InputStream stream =  MyClass.class.getResourceAsStream(excelFilePath);

and also format the excelFilePath to begin with a '/'.

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