[英]create File instance with classpath
我正在尝试将文件加载到位于项目中的文件实例中。 在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);
}
}
我正在尝试将文件加载到位于项目中的文件实例中
和
我想将我的项目导出到可运行的JAR,但现在不再起作用
这表明您要查找的文件已嵌入Jar文件中。
因此,简短的答案是,不要。 使用getClass().getResourceAsStream(path)
并使用生成的InputStream
代替
嵌入式资源不是文件,而是存储在Jar(Zip)文件中的字节
您需要使用更多类似...
private void mapLoader(String path) {
try (Scanner s = new Scanner(getClass().getResourceAsStream(path)) {
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
} catch (IOException e) {
System.err.println("The map could not be loaded.");
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.