When to use “getResourceAsStream” method?

后端 未结 4 1273
死守一世寂寞
死守一世寂寞 2020-12-11 06:39

I was confused using the said method because while loading some properties file people are following a different approaches...

Properties prop 
 = new Proper         


        
相关标签:
4条回答
  • 2020-12-11 06:51

    You can use the first approach if you are 100 % sure that the file location doesn't change across environments. This means there is a operations over head to make sure those directory paths are created across all environments. On the flip side, you have the flexibility of updating the properties file without opening the jar.

    The second approach is very portable as you are reading from the classpath. But it has the disadvantage of re-bundling the jar file for every property update.

    So, it basically depends upon your use-case.

    0 讨论(0)
  • 2020-12-11 06:58

    getResourceAsStream searchs you classpath for the given file/resource and it can also provide InputStreams of resources from inside a JAR.

    So, if your properties exist in some folder in the physical filesystem (e.g. user folder, ...) use FileInputStream and if the file is embedded in your classpath (e.g. as a resource inside the JAR) use getResourceAsStream.

    0 讨论(0)
  • 2020-12-11 07:01

    When reading a file from the filesystem use a FileInputStream(File()) using relative or absolute paths.

    when your program is distributed as a jar and you need to load a file that is inside that jar, you need to use getResourceAsStream(), it will search the classpath for the file, and the path is relative to the classpath.

    0 讨论(0)
  • 2020-12-11 07:01

    When you are reading a file from the Jar. Please use classloader's getResource or getResoureAsstream. Find the below code snippet to read a file from Jar. The above approaches cannot read a file from jar.

        InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream("com/net/resources/config.properties");
    
        InputStream is = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("com/net/resources/config.properties");
    
        URL url = this.getClass().getClassLoader()
                .getResource("com/net/resources/config.properties");
    
    0 讨论(0)
提交回复
热议问题