Home  >  Article  >  Java  >  How to Load Properties Files from Within Java Packages?

How to Load Properties Files from Within Java Packages?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 00:14:28873browse

How to Load Properties Files from Within Java Packages?

Loading Properties Files from Within Java Packages

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn