this.getClass()。getClassLoader()。getResource(“...”)和NullPointerException [英] this.getClass().getClassLoader().getResource("...") and NullPointerException
问题描述
在src / test / resources文件夹中,我已经放了一个文件install .XML。在文件夹src / test / java中,我创建了一个包含单个类的单个包:
@Test
public void doit()throws Exception {
URL url = this.getClass()。getClassLoader()。getResource(install.xml);
System.out.println(url.getPath());
}
但是当我运行代码作为junit 4单元测试我只是得到一个NullPointerException。以前的工作已经很好了一百万次。任何想法?
我遵循了本指南:
http://www.fuyun.org/2009/11/how-toread -input-files-in-maven-junit /
但仍然收到相同的错误。
当您使用
this.getClass()。getResource(myFile ext)
getResource
将尝试查找相对于包的资源。
如果您使用:
this.getClass()。getResource(/ myFile.ext)
getResource
将其视为绝对路径,只需调用像你这样做的类加载器就可以了。
this.getClass()。getClassLoader()。getResource(myFile .ext)
您不能使用领先的 /
$ code> ClassLoader 路径是因为所有 ClassLoader
路径是绝对的,所以 /
不是路径中有效的第一个字符。
I have created a minimal maven project with a single child module in eclipse helios.
In the src/test/resources folder I have put a single file "install.xml". In the folder src/test/java I have created a single package with a single class that does:
@Test
public void doit() throws Exception {
URL url = this.getClass().getClassLoader().getResource("install.xml");
System.out.println(url.getPath());
}
but when I run the code as a junit 4 unit test I just get a NullPointerException. This has worked fine a million of times before. Any ideas?
I have followed this guide:
http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/
but still get the same error.
When you use
this.getClass().getResource("myFile.ext")
getResource
will try to find the resource relative to the package.
If you use:
this.getClass().getResource("/myFile.ext")
getResource
will treat it as an absolute path and simply call the classloader like you would have if you'd done.
this.getClass().getClassLoader().getResource("myFile.ext")
The reason you can't use a leading /
in the ClassLoader
path is because all ClassLoader
paths are absolute and so /
is not a valid first character in the path.
这篇关于this.getClass()。getClassLoader()。getResource(“...”)和NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!