When to use “getResourceAsStream” method?

假如想象 提交于 2020-06-08 08:22:15

问题


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

Properties prop 
 = new Properties(new FileInputStream(new File("<path of the properties file>"));

and few are using..

Properties prop 
 = new Properties(getClass().getResourceAsStream("<path of the properties file>"));

Which one to use when?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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");


来源:https://stackoverflow.com/questions/10247161/when-to-use-getresourceasstream-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!