5

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?

Sriram
  • 2,909
  • 8
  • 27
  • 35

4 Answers4

11

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.

Neet
  • 3,937
  • 15
  • 18
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.

Gertjan Assies
  • 1,890
  • 13
  • 23
0

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.

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
-1

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");
Pani
  • 186
  • 1
  • 3
  • 12