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
In this context:
File file = new File(this.getClass().getClassLoader().getResource("file.xml").getFile());
// or this also don't work
File file = new File("file.xml");
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);
If I understand the Javadocs correctly, this should be the same as using getClass().getClassloader().getResource()
but in my experience it is different
I would suggest that you add a line so it says something along the lines (untested):
File f = new File(....);
System.out.println("f=" + f.getAbsolutePath());
// do stuff with f
This will tell you exactly where the file is expected to be and allow you to figure out what exactly is going on.
有时您可能需要在前面添加一个额外的/
File file = new File(this.getClass().getClassLoader().getResource("/file.xml").getFile());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.