我的文件位于我的/res 中,更具体地说,位于/res/Menus/CharSelect 中。我已经进入构建路径并确保 res 文件夹是类路径。但是,我的新扫描仪(文件)导致 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
的形式访问该文件。您必须从中获取带有 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)
关于Java 在/res 文件夹中查找文件并使用 Scanner 处理它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428738/