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

/src/initialization/Lifepaths.txt

我的代码通过调用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();}
}

不管我用什么,输出总是输出null。我不知道为什么上面的方法不管用,所以我也尝试了一下:

“初始化/ src / / Lifepaths.txt” “初始化/ Lifepaths.txt” “Lifepaths.txt”

这两种方法都不起作用。到目前为止,我已经阅读了许多关于这个主题的问题,但没有一个是有帮助的——通常,他们只是说使用根路径加载文件,而我已经这样做了。或者只是从当前目录加载文件(只是加载文件名),我也尝试过。该文件将被编译到JAR中的适当位置,并具有适当的名称。

我怎么解决这个问题?


当前回答

聚会迟到了。这取决于你使用的JDK版本(也许是时候查看StackOverflow“已经回答的问题”了?)JPMS会影响您能够加载(或不能加载)的资源。

将我的代码打包为模块,我必须这样做:

.getResourceAsStream .getModule .getClass Thread.currentThread()()()(“resourceName”);

然后就成功了

其他回答

不知道是否有帮助,但在我的情况下,我的资源在/src/文件夹,并得到这个错误。 然后我将图片移动到bin文件夹,它修复了这个问题。

不要使用绝对路径,让它们相对于项目中的“资源”目录。快速和肮脏的代码,显示MyTest.txt的内容从目录“资源”。

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

我的调用者类在src/main/…

什么帮助我从src/test/resources/folder/file.properties加载资源

`properties.load(getClass().getClassLoader().getResourceAsStream("folder/file.properties"));`

https://howtodoinjava.com/java/io/read-file-from-resources-folder/

Java 11

对我有用的是将文件添加到我的项目/Java资源/src下,然后使用

this.getClass().getClassLoader().getResourceAsStream("myfile.txt");

我不需要显式地将这个文件添加到路径(添加到/src显然这样做)

对我有用的是我把文件放在下面

src/main/java/myfile.log

and

InputStream is = getClass().getClassLoader().getResourceAsStream("myfile.log");
        
        if (is == null) {
            throw new FileNotFoundException("Log file not provided");
        }