[英]Reading from src/main/resources gives NullPointerException
In my Maven project, I have a xls file in src/main/resources. 在我的Maven项目中,我在src / main / resources中有一个xls文件。 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. 但是我想用getResourceAsStream将其作为InputStream读取。 When I do this, with or without the slash I always get a NPE.
当我这样做时,无论有没有斜线,我总是得到一个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. 无论是否存在斜杠,或者如果我使用了getClassLoader()方法,我仍然会得到一个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. 控制台说... / target / classes / WBU_template.xls然后得到我的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. FileInputStream将从Java进程的工作目录中加载您传递给构造函数的文件路径。
getResourceAsStream() will load a file path relative from your application's classpath. getResourceAsStream()将从应用程序的类路径加载相对的文件路径。
When you use .getClass().getResource(fileName)
it considers the location of the fileName is the same location of the of the calling class. 当您使用
.getClass().getResource(fileName)
它认为fileName的位置与调用类的位置相同。
When you use .getClass().getClassLoader().getResource(fileName)
it considers the location of the fileName is the root - in other words bin folder. 当你使用
.getClass().getClassLoader().getResource(fileName)
它认为.getClass().getClassLoader().getResource(fileName)
的位置是根 - 换句话说就是bin文件夹。
The file should be located in src/main/resources
when loading using Class loader 使用类加载器加载时,该文件应位于
src/main/resources
In short, you have to use .getClass().getClassLoader().getResource(fileName)
to load the file in your case. 简而言之,您必须使用
.getClass().getClassLoader().getResource(fileName)
来加载您的案例中的文件。
我通常像这样从WEB-INF加载文件
session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.