Loading properties files that reside deep within a package structure can be a challenge. Suppose you want to access a properties file located in com.al.common.email.templates.
To resolve this, use the following code within your class in the specified package:
<code class="java">Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("foo.properties"); prop.load(in); in.close();</code>
Remember to include proper exception handling.
If your class is not within the desired package, adjust the InputStream acquisition:
<code class="java">InputStream in = getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");</code>
Note that relative paths in getResource() or getResourceAsStream() are resolved within the package where your class resides. Hence, java.lang.String.class.getResource("foo.txt") searches for the nonexistent file /java/lang/String/foo.txt. Absolute paths (starting with '/') bypass the current package.
The above is the detailed content of How to Load Properties Files from Within Java Packages?. For more information, please follow other related articles on the PHP Chinese website!