getResourceAsStream 返回 null [英] getResourceAsStream returns null

查看:39
本文介绍了getResourceAsStream 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的 Java 项目的已编译 JAR 包中加载文本文件.相关目录结构如下:

I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:

/src/initialization/Lifepaths.txt

我的代码通过调用Class::getResourceAsStream 返回一个 InputStream.

My code loads a file by calling Class::getResourceAsStream to return a InputStream.

public class Lifepaths {
    public static void execute() {
        System.out.println(Lifepaths.class.getClass().
            getResourceAsStream("/initialization/Lifepaths.txt"));
    }

    private Lifepaths() {}

    //This is temporary; will eventually be called from outside
    public static void main(String[] args) {execute();}
}

无论我使用什么,打印出来的东西总是打印 null.我不确定为什么上面的方法不起作用,所以我也试过:

The print out will always print null, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:

  • "/src/initialization/Lifepaths.txt"
  • 初始化/Lifepaths.txt"
  • Lifepaths.txt"

这些都不起作用. 阅读 无数 问题 到目前为止这个主题,但没有一个有帮助 - 通常,他们只是说使用根路径加载文件,我已经在做.那,或者只是从当前目录加载文件(只需加载 filename),我也尝试过.该文件正在被编译到具有适当名称的适当位置的 JAR 中.

Neither of these work. I've read numerous questions so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load filename), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name.

我该如何解决这个问题?

How do I solve this?

推荐答案

Lifepaths.class.getClass().getResourceAsStream(...) 使用系统类加载器加载资源,显然失败,因为它看不到您的 JAR

Lifepaths.class.getClass().getResourceAsStream(...) loads resources using system class loader, it obviously fails because it does not see your JARs

Lifepaths.class.getResourceAsStream(...) 使用加载 Lifepaths 类的相同类加载器加载资源,并且它应该可以访问 JAR 中的资源

Lifepaths.class.getResourceAsStream(...) loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs

这篇关于getResourceAsStream 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆