Netbeans:尝试加载文件但未找到(Java)
问题描述:
当我尝试在Netbeans(6.9)中使用Java加载文件时,我总是遇到相同的问题. 似乎找不到文件.我收到错误消息:
I have every time the same problem when I'm trying to load files with Java in Netbeans (6.9). It seems that the files aren't found. I get the error:
java.lang.NullPointerException
java.lang.NullPointerException
在这种情况下:
File file = new File(this.getClass().getClassLoader().getResource("file.xml").getFile());
// or this also don't work
File file = new File("file.xml");
文件file.xml
与Main.java
文件位于同一目录中.
我该如何加载该文件?
The file file.xml
is in the same directory as the Main.java
file.
How could I load this file?
答
这应该有效(对我有用):
This should work (it does for me):
String path = URLDecoder.decode(getClass().getResource("file.xml").getFile(), "UTF-8");
File f = new File(path);
如果我正确理解Javadocs,这应该与使用getClass().getClassloader().getResource()
相同,但是根据我的经验,这是不同的
If I understand the Javadocs correctly, this should be the same as using getClass().getClassloader().getResource()
but in my experience it is different