我正在从我的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中的适当位置,并具有适当的名称。

我怎么解决这个问题?


当前回答

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

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

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

其他回答

你正在使用的ClassLoader似乎有问题。使用contextClassLoader加载类。这与它是静态方法还是非静态方法无关

.getContextClassLoader Thread.currentThread () () .getResourceAsStream……

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

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

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

粗略地说:

getClass(). getresource ("/") ~= Thread.currentThread(). getcontextclassloader (). getresource (".")

假设你的项目结构如下:

├── src
│   ├── main
│   └── test
│       ├── java
│       │   └── com
│       │       └── github
│       │           └── xyz
│       │               └── proj
│       │                   ├── MainTest.java
│       │                   └── TestBase.java
│       └── resources
│           └── abcd.txt
└── target
    └── test-classes  <-- this.getClass.getResource("/")
        │              `--Thread.currentThread().getContextClassLoader().getResources(".")
        ├── com
        │   └── github
        │       └── xyz
        │           └── proj  <-- this.getClass.getResource(".")
        │               ├── MainTest.class
        │               └── TestBase.class
        └── resources
            └── abcd.txt

// in MainTest.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") ->  null

我的调用者类在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

如果您正在使用IDEA,请确保将您的资源文件夹标记为“resources”,以便IDE可以正确识别该路径。

假设你有一个名为book的文件。Json在resources/中,然后使用其中的资源,你可以这样做

InputStream input = Main.class.getResourceAsStream("/book.json");