getResourceAsStream returns null

前端 未结 16 2307
臣服心动
臣服心动 2020-11-22 04:00

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/Life         


        
16条回答
  •  长情又很酷
    2020-11-22 04:43

    Roughly speaking:

    getClass().getResource("/") ~= Thread.currentThread().getContextClassLoader().getResource(".")

    Suppose your project structure is like the following:

    ├── src
    │   ├── main
    │   └── test
    │   └── test
    │       ├── java
    │       │   └── com
    │       │       └── github
    │       │           └── xyz
    │       │               └── proj
    │       │                   ├── MainTest.java
    │       │                   └── TestBase.java
    │       └── resources
    │           └── abcd.txt
    └── target
        └── test-classes
            ├── com
            └── abcd.txt
    
    
    // in MainClass.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
    
    

提交回复
热议问题