getResourceAsStream returns null

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

    Make sure your resource directory (e.g. "src") is in your classpath (make sure it's a source directory in your build path in eclipse).

    Make sure clazz is loaded from the main classloader.

    Then, to load src/initialization/Lifepaths.txt, use

    clazz.getResourceAsStream("/initialization/Lifepaths.txt");
    

    Why: clazz.getResourcesAsStream(foo) looks up foo from within the classpath of clazz, relative to the directory clazz lives in. The leading "/" makes it load from the root of any directory in the classpath of clazz.

    Unless you're in a container of some kind, like Tomcat, or are doing something with ClassLoaders directly, you can just treat your eclipse/command line classpath as the only classloader classpath.

提交回复
热议问题