一台计算机上的java.io.FileNotFoundException但没有另一台[长篇]

时间:2016-04-25 21:38:56

标签: java windows filenotfoundexception

我正在开发一个mod来在虚幻世界中生成随机植物。我在游戏论坛上发布了mod的初始版本,并且我被告知Windows版本的mod存在问题。问题特别在于名称生成;它只为每个名称返回null。向我报告此问题的用户发布了这个堆栈跟踪(重复了几次相同的错误;无需全部阅读):

enter image description here

这是发生错误的方法:

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 Home(版本1511,Build 10586)。另一个运行Windows 8.1(没有给出其他细节)的用户可以正常运行,没有FileNotFoundExceptions或null名称。

如果它是相关的,我正在运行Ubuntu 14.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 个答案:

答案 0 :(得分:1)

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一起使用时除外),因此尝试使用资源块。