getResourceAsStream returns null

前端 未结 16 2533
臣服心动
臣服心动 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:41

    The rules are as follows:

    1. check the location of the file you want to load inside the JAR (and thus also make sure it actually added to the JAR)
    2. use either an absolute path: path starts at the root of the JAR
    3. use an relative path: path starts at the package directory of the class you're calling getResource/ getResoucreAsStream

    And try:

    Lifepaths.class.getResourceAsStream("/initialization/Lifepaths.txt")
    

    instead of

    Lifepaths.class.getClass().getResourceAsStream("/initialization/Lifepaths.txt")
    

    (not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)

提交回复
热议问题