从src / main / resources读取会产生NullPointerException [英] Reading from src/main/resources gives NullPointerException
问题描述
在我的Maven项目中,我在src / main / resources中有一个xls文件。
当我这样读它时:
InputStream in = new
FileInputStream(src / main /资源/ WBU_template.xls);
一切正常。
但是我想用getResourceAsStream将其作为InputStream读取。当我这样做时,无论有没有斜线,我总是得到一个NPE。
private static final String TEMPLATEFILE =/ WBU_template。 XLS;
InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);
无论斜杠是否存在,或者我是否使用了getClassLoader()方法,我仍然得到一个NullPointer。
我也试过这个:
URL u = this.getClass()。getResource(TEMPLATEFILE);
System.out.println(u.getPath());
控制台说... / target / classes / WBU_template.xls
然后获取我的NullPointer。
我做错了什么?
FileInputStream将从Java进程的工作目录中以相对方式加载传递给构造函数的文件路径。
getResourceAsStream()将从应用程序的类路径加载相对的文件路径。
当你使用 .getClass()。getResource(fileName)
它认为fileName的位置与调用类的位置相同。
当你使用 .getClass()。getClassLoader()。getResource(fileName)
它认为fileName的位置是根 - 换句话说bin文件夹。
使用类加载器
src / main / resources 中>简而言之,你必须使用 .getClass()。getClassLoader()。getResource(fileName)
来加载文件你的情况。
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 ?
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.
这篇关于从src / main / resources读取会产生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!