开发者

Netbeans: Try to load file but not found (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

In this context:

File file = new File(this开发者_如何学C.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.


Sometimes you might need to add an extra / in front

File file = new File(this.getClass().getClassLoader().getResource("/file.xml").getFile());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜