【问题标题】:create File instance with classpath使用类路径创建 File 实例
【发布时间】:2015-08-10 10:38:57
【问题描述】:

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

【问题讨论】:

    标签: java file nullpointerexception classpath getresource


    【解决方案1】:

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

    我想将我的项目导出到可运行的 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();
        }
    }
    

    【讨论】:

    • 我不认为我明白你的意思。你建议过这样的事情吗?文件 file = new File(getClass().getResourceAsStream(path));
    • 不,您不能再以File 的身份访问资源,我的意思是更像s = new Scanner(getClass().getResourceAsStream(path))。你不能把嵌入式资源想象成文件,它们根本不是,它们是 Jar/Zip 文件中的条目
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多