Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - Reading from src/main/resources gives NullPointerException

In my Maven project, I have a xls file in src/main/resources. When I read it like this:

 InputStream in = new
 FileInputStream("src/main/resources/WBU_template.xls");

everything is ok.

However I want to read it as InputStream with getResourceAsStream. When I do this, with or without the slash I always get a NPE.

     private static final String TEMPLATEFILE = "/WBU_template.xls";
     InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);

No matter if the slash is there or not, or if I make use of the getClassLoader() method, I still get a NullPointer.

I also have tried this :

URL u = this.getClass().getResource(TEMPLATEFILE);
System.out.println(u.getPath());

the console says.../target/classes/WBU_template.xls and then get my NullPointer.

What am I doing wrong ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.

getResourceAsStream() will load a file path relative from your application's classpath.

When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.

When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

The file should be located in src/main/resources when loading using Class loader

In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...