getResourceAsStream 返回 null - getResourceAsStream returns null

10/14 00:05
阅读数 0

问题:

I'm loading a text file from within a package in a compiled JAR of my Java project.我正在从我的 Java 项目的已编译 JAR 中的包中加载文本文件。 The relevant directory structure is as follows:相关目录结构如下:

/src/initialization/Lifepaths.txt

My code loads a file by calling Class::getResourceAsStream to return a InputStream .我的代码通过调用Class::getResourceAsStream来加载一个文件以返回一个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();}
}

The print out will always print null , no matter what I use.无论我使用什么,打印输出都将始终打印null I'm not sure why the above wouldn't work, so I've also tried:我不确定为什么上述方法不起作用,所以我也尝试过:

  • "/src/initialization/Lifepaths.txt"
  • "initialization/Lifepaths.txt"
  • "Lifepaths.txt"

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.那,或者只是从当前目录加载filename (只是加载filename ),我也试过。 The file is being compiled into the JAR in the appropriate location with the appropriate name.该文件正在被编译到具有适当名称的适当位置的 JAR 中。

How do I solve this?我该如何解决这个问题?


解决方案:

参考一: https://en.stackoom.com/question/17WkV
参考二: https://stackoom.com/question/17WkV
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部