[英]Java Finding a file in /res folder and using Scanner with it
我的文件位于我的/ res中,更具体地说,位于/ res / Menus / CharSelect中。 我已经进入构建路径,并确保res文件夹是类路径。 但是,我的新Scanner(file)导致NullPointerException。 当我做file.exists(); 它返回FALSE ...,我不知道为什么。 我100%确实存在该文件,并且该文件位于CharSelect文件夹中。 有人可以帮忙吗? 提前致谢。
file = new File(getClass().getResource("/Menus/CharSelect/Unlocked.txt").getPath());
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
不要那样做 创建jar时,您将不能以File
对象的形式访问该文件,而只能以URL
形式访问该URL
,而必须使用openStream()
获得InputStream
。
而是将Scanner(InputStream)
与以下项一起使用:
try (InputStream is = getClass().getResource("/Menus/CharSelect/Unlocked.txt").openStream()) {
scanner = new Scanner(is);
...
} // is.close() called automatically by try-with-resource block (since Java 7)
someClass.getResource
解析相对于someClass
位置的路径。 将文件移到PATH_TO_THIS_CLASS_PATH / Menus / CharSelect / Unlocked.txt,操作必须成功
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.