51

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.

Jainendra
  • 24,713
  • 30
  • 122
  • 169
Kashif Raza
  • 535
  • 1
  • 4
  • 3

2 Answers2

79

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"));
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
Keval Trivedi
  • 1,290
  • 2
  • 13
  • 29
  • 3
    Does the `InputStream` opened by `getResourceAsStream` need to be closed after loaded ? – CDT Jul 09 '15 at 09:46
  • 4
    @CDT The `Properties.load()` javadoc states that "_The specified stream remains open after this method returns._" – Yonatan Sep 01 '15 at 11:37
65
final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}
obataku
  • 29,212
  • 3
  • 44
  • 57
  • 1
    Does the `InputStream` opened by `getResourceAsStream` need to be closed after loaded ? – CDT Jul 09 '15 at 09:47
  • 2
    @CDT The `Properties.load()` javadoc states that "_The specified stream remains open after this method returns._" – Yonatan Sep 01 '15 at 11:36
  • 5
    This is the "try with resources" syntax introduced with Java 7. The stream will be automatically closed when the try {} block exits. Prior to Java 7, you would close this stream by hand in a finally {} block. https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Drew Wills May 27 '16 at 17:42
  • @DrewWills yes, we know; the comments were regarding the original code posted which did not use the Java 7 *try-with-resources* construct – obataku May 29 '16 at 07:29
  • 3
    In my experience, the file needs a leading "/" to be found from the classpath. – Software Prophets Aug 20 '16 at 12:53
  • Won't really work in every case if you don't call the method through the class loader instead of the class itself. – Giulio Piancastelli Oct 18 '17 at 16:01
  • @GiulioPiancastelli don't know if that's true in practice but if so that behavior violates the [API specification](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String))--*This method delegates to this object's class loader.* – obataku Oct 20 '17 at 13:27
  • @oldrinb : I am getting FileNotFoundException. My file is at projectName/config.properties... – Abhijit Bashetti Sep 27 '18 at 05:53