[java] How to load property file from classpath?

getResourceAsStream() is the method of java.lang.Class class. This method finds the resource with given name into the classpath. Actually this method delegates to this object's class loader. In this example PropUtil object's class loader. But before delegation, an absolute resource name is constructed from the given resource name using following algorithm.

This question is related to java

The answer is


If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}