windows java。木卫一。一台计算机上的FileNotFoundException而不是另一台计算机上的FileNotFoundException[长文章]
我正在制作一个模型,在虚幻世界中生成随机植物。我在游戏的论坛上发布了最初版本的mod,有人告诉我Windows版本的mod有一个问题。问题具体在于名字的产生;它只会为每个名称返回null。向我报告此问题的用户发布了此stacktrace(同一错误重复了几次;无需全部阅读):
这是发生错误的方法:
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;
}
}
这个程序包含在一个JAR中,其中包含modwin、srcwin和META-INF目录。类文件包含在modwin中,而源代码和txt文件包含在srcwin中。报告此问题的用户正在运行Windows 10 Home(版本1511,版本10586)。另一个运行Windows 8.1(没有给出其他细节)的用户可以很好地运行它,没有FileNotFoundException或空名称
如果相关的话,我正在运行Ubuntu14.04,这段代码中唯一的区别是文件路径是src/Prefixes.txt
,而不是srcwin\\Prefixes.txt
,它对我来说运行得很好
如果您想查看stacktrace中提到的其他代码行:
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
# 1 楼答案
new Scanner(new File("srcwin\\Prefixes.txt"))
将从当前目录打开文件srcwin\Prefixes.txt
Jar文件中的目录不能以这种方式访问
因此,要么当前目录不是您所认为的,要么文件不在那里(在文件系统的
srcwin
文件夹中)要在Jar中加载文件内容(我们假定它位于类路径上),请使用^{}
请注意对文件名的更改。它以
/
开头,并使用/
还请注意,在使用
Scanner
时,应该始终关闭它(与System.in
一起使用时除外),因此使用try with resources块