使用classpath创建File实例

时间:2015-05-28 05:19:42

标签: java file nullpointerexception classpath getresource

我正在尝试将文件加载到位于我的项目中的文件实例中。在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);
    }
}

1 个答案:

答案 0 :(得分:0)

  

我正在尝试将文件加载到位于我的项目中的文件实例

  

我想将我的项目导出到可运行的JAR,但它不再起作用了

这表明您尝试查找的文件嵌入在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();
    }
}
相关问题