使用类路径创建文件实例

create File instance with classpath

我正在尝试将文件加载到位于我的项目中的文件实例中。当 运行 在 Eclipse 中我可以这样做:

File file = new File(path);

我想将我的项目导出到可运行的 JAR,但它不再起作用了。当我以 Eclipse 方式执行时,Java 抛出 NullPointerException。经过几个小时的谷歌搜索后,我发现了这个:

File file = new File(ClassLoader.getSystemResource(path).getFile());

但这并没有解决问题。我仍然得到相同的 NullPointerException。这是我需要此文件的方法:

private void mapLoader(String path) {
    File file = new File(ClassLoader.getSystemResource(path).getFile());
    Scanner s;
    try {
        s = new Scanner(file);
        while (s.hasNext()) {
            int character = Integer.parseInt(s.next());
            this.getMap().add(character);
        }
    } catch (FileNotFoundException e) {
        System.err.println("The map could not be loaded.");
    }
}

有没有办法用getResource()方法加载文件?或者我应该完全重写我的 mapLoader 方法吗?

编辑: 我把我的方法改成了这个,感谢@madprogrammer

private void mapLoader(String path) {
    Scanner s = new Scanner(getClass().getResourceAsStream(path));
    while (s.hasNext()) {
        int character = Integer.parseInt(s.next());
        this.getMap().add(character);
    }
}

I am trying to load a file into a file instance which is located in my project

I wanted to export my project to a runnable JAR but it does not work anymore

这表明您要查找的文件已嵌入到 Jar 文件中。

所以简短的回答是,不要。使用 getClass().getResourceAsStream(path) 并使用结果 InputStream 代替

嵌入式资源不是文件,它们是存储在 Jar(Zip) 文件中的字节

你需要使用更像...

private void mapLoader(String path) {
    try (Scanner s = new Scanner(getClass().getResourceAsStream(path)) {
        while (s.hasNext()) {
            int character = Integer.parseInt(s.next());
            this.getMap().add(character);
        }
    } catch (IOException e) {
        System.err.println("The map could not be loaded.");
        e.printStackTrace();
    }
}