【发布时间】:2015-08-10 10:38:57
【问题描述】:
我正在尝试将文件加载到位于我的项目中的文件实例中。在 Eclipse 中运行时,我可以这样做:
File file = new File(path);
我想将我的项目导出到一个可运行的 JAR,但它不再工作了。当我以 Eclipse 方式进行操作时,Java 会抛出 NullPointerException。经过几个小时的谷歌搜索,我发现了这个:
File file = new File(ClassLoader.getSystemResource(path).getFile());
但这并没有解决问题。我仍然得到相同的 NullPointerException。这是我需要这个文件的方法:
private void mapLoader(String path) {
File file = new File(ClassLoader.getSystemResource(path).getFile());
Scanner s;
try {
s = new Scanner(file);
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
} catch (FileNotFoundException e) {
System.err.println("The map could not be loaded.");
}
}
有没有办法用 getResource() 方法加载文件?还是我应该完全重写我的 mapLoader 方法?
编辑: 我把我的方法改成了这个,感谢@madprogrammer
private void mapLoader(String path) {
Scanner s = new Scanner(getClass().getResourceAsStream(path));
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
}
【问题讨论】:
标签: java file nullpointerexception classpath getresource