我正在开发一个在虚幻世界中生成随机植物的模组。我在游戏论坛上发布了该模组的初始版本,并且有人告诉我该模组的 Windows 版本存在问题。问题具体在于名称生成;它只是为每个名称返回 null。向我报告此问题的用户发布了此堆栈跟踪(相同的错误重复了多次;无需全部阅读):
这是发生错误的方法:
private static String getName(Random rn, boolean full) {
try {
String name;
int prefix = rn.nextInt(179);
int suffix = rn.nextInt(72);
Scanner sc1 = new Scanner(new File("srcwin\\Prefixes.txt")); // error occurs on this line
for (int i=0; i<prefix; i++) {
sc1.nextLine();
}
name = sc1.next();
if (name.contains("'")) {
name += " ";
}
if (full || rn.nextInt(3) == 0) {
if (rn.nextInt(3) == 0 && !name.contains(" ")) {
name += " ";
}
Scanner sc2 = new Scanner(new File("srcwin\\Suffixes.txt"));
for (int i=0; i<suffix; i++) {
sc2.nextLine();
}
name += sc2.next();
}
return name;
} catch (FileNotFoundException ex) {
Logger.getLogger(UrWPlantMod.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
该程序包含在包含目录 modwin、srcwin 和 META-INF 的 JAR 中。类文件包含在 modwin 中,而源代码和 txt 文件包含在 srcwin 中。报告此问题的用户运行的是 Windows 10 家庭版(版本 1511,内部版本 10586)。另一个运行 Windows 8.1 的用户(未给出其他具体信息)可以正常运行,没有 FileNotFoundExceptions 或 null 名称。
如果相关的话,我正在运行 Ubuntu 14.04,此代码中唯一的区别是文件路径是 src/Prefixes.txt
而不是 srcwin\\Prefixes.txt
,它对我来说运行得很好。
如果您想查看堆栈跟踪中提到的其他代码行:
berries[i] = new Plant(getName(rn, false) + "berry " + getBerryName(rn), rn.nextInt(4)+1, getImg(rn, "berry"));
和
createBerries(rn); // the above line of code is in the method called here
最佳答案
new Scanner(new File("srcwin\\Prefixes.txt"))
将从当前目录打开文件srcwin\Prefixes.txt
.
无法以这种方式访问 Jar 文件内的目录。
因此,要么当前目录不是您想象的那样,要么文件不存在(位于文件系统上的文件夹 srcwin
中)。
要加载 Jar 中的文件内容(我们假设位于类路径上),请使用 getResourceAsStream()
.
try (Scanner sc1 = new Scanner(MyClass.class.getResourceAsStream("/srcwin/Prefixes.txt"))) {
// code here
}
请注意文件名的更改。它以 /
开头并使用 /
。
另请注意,使用完后应始终关闭 Scanner
(除非与 System.in
一起使用),因此需要使用 try-with-resources block 。
关于java.io.FileNotFoundException 在一台计算机上,但在另一台计算机上没有 [长帖子],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36851547/