getResourceAsStream returns null

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

    The default JVM classloader will use parent-classloader to load resources first: deletegate-parent-classloader.

    Lifepaths.class.getClass()'s classloader is bootstrap classloader, so getResourceAsStream will search $JAVA_HOME only, regardless of user provided classpath. Obviously, Lifepaths.txt is not there.

    Lifepaths.class 's classloader is system classpath classloader, so getResourceAsStream will search user-defined classpath and Lifepaths.txt is there.

    When using java.lang.Class#getResourceAsStream(String name), name which is not start with '/' will be added with package name as prefix. If you want avoid this, please using java.lang.ClassLoader#getResourceAsStream. For example:

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String resourceName = "Lifepaths.txt";
    InputStream resourceStream = loader.getResourceAsStream(resourceName); 
    

提交回复
热议问题