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

How to Load Properties Files from Within Java Packages?

Barbara Streisand
Release: 2024-10-26 00:14:28
Original
964 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template