Read and write .properties files in Java from the classpath or a file path, handle UTF-8 correctly, add typed getters and defaults, and load properties from assets on Android.
Written for JDK 21 (the code also runs on JDK 17); Android API 24 and newer
In this JavaAnt guide, we explore reading and writing properties files. A .properties file is the simplest configuration format Java has: one key=value per line, read by java.util.Properties, which has been in the JDK since version 1.0. It is still everywhere, from Spring Boot's application.properties to Gradle's gradle.properties. This tutorial covers loading one from the classpath and from disk, the encoding detail that trips people up, a small typed wrapper, and the Android version.
The file format
# Lines starting with # or ! are comments
app.name = Corner Shop
db.url=jdbc:postgresql://localhost/shop
db.pool.size=12
feature.search=true
# A trailing backslash continues the value on the next line
greeting=Hello, \
worldKeys and values are separated by =, : or whitespace, and spaces around the separator are ignored. Everything is a string: Properties has no idea that 12 is a number or true a boolean, so conversion is your job. Keys are case-sensitive.
Load it from the classpath
Put the file in src/main/resources (Maven and Gradle copy that folder onto the classpath), then read it through the class loader:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public final class AppConfig {
private final Properties props;
private AppConfig(Properties props) {
this.props = props;
}
public static AppConfig fromClasspath(String resource) {
try (InputStream in = AppConfig.class.getClassLoader().getResourceAsStream(resource)) {
if (in == null) {
throw new IllegalStateException(resource + " is not on the classpath");
}
Properties props = new Properties();
props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
return new AppConfig(props);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}Two details matter here. getResourceAsStream returns null instead of throwing when the file is missing, so check for it, or you get a NullPointerException from inside load that hides the real problem. And the path is relative to the classpath root when you call it on the class loader ("app.properties"), but relative to the class's package when you call AppConfig.class.getResourceAsStream without a leading slash. Using the class loader avoids that confusion.
The encoding trap
Properties.load(InputStream) reads the bytes as ISO-8859-1, not UTF-8. That rule dates from Java 1.0 and has never changed, so a value like Ünïcode saved as UTF-8 comes back as Ãnïcode. Wrapping the stream in an InputStreamReader with StandardCharsets.UTF_8, as above, and calling load(Reader) fixes it.
The confusion comes from Java 9, which made ResourceBundle read properties files as UTF-8 (JEP 226). That change applies to resource bundles for translations only. Plain Properties.load(InputStream) still uses ISO-8859-1, and the old workaround of writing Ü escapes in the file still works in both.
Read from a file on disk
For configuration that operators edit next to the application, load from a path instead of the classpath:
public static AppConfig fromFile(Path path) {
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Properties props = new Properties();
props.load(reader);
return new AppConfig(props);
} catch (IOException e) {
throw new UncheckedIOException("Cannot read " + path.toAbsolutePath(), e);
}
}Files.newBufferedReader already decodes UTF-8, so the encoding problem does not arise. Relative paths resolve against the working directory the JVM started in, which is often not where you expect when the app runs from an IDE or a service manager. Print path.toAbsolutePath() in the error message to save yourself the guesswork.
Typed getters and overrides
Scattering Integer.parseInt(props.getProperty(...)) through the code is how configuration bugs start. Put the conversion in one place, and fail fast with the key's name when a required setting is missing:
public String get(String key) {
String value = System.getProperty(key, props.getProperty(key));
if (value == null) {
throw new IllegalStateException("Missing setting: " + key);
}
return value.strip();
}
public int getInt(String key, int fallback) {
String value = props.getProperty(key);
return value == null ? fallback : Integer.parseInt(value.strip());
}
public boolean getBoolean(String key) {
return Boolean.parseBoolean(get(key));
}System.getProperty(key, fileValue) lets anyone override a value at startup with -Ddb.url=... without editing the file, which is handy in tests and containers. strip() removes trailing spaces, which Properties keeps and which are invisible in most editors.
For defaults, Properties has a built-in mechanism: pass a second Properties object to the constructor, and getProperty falls back to it for missing keys.
Properties defaults = new Properties();
defaults.setProperty("db.pool.size", "10");
Properties props = new Properties(defaults);Note that props.get("db.pool.size") (inherited from Hashtable) ignores the defaults; only getProperty consults them.
Write a properties file
store writes the keys back out, with a comment line and a timestamp at the top:
Properties state = new Properties();
state.setProperty("last.run", LocalDate.now().toString());
try (Writer writer = Files.newBufferedWriter(Path.of("state.properties"), StandardCharsets.UTF_8)) {
state.store(writer, "Written by the app");
}store does not preserve your comments, blank lines or key order from an earlier file. If people edit the file by hand, treat it as read-only from the program and keep machine-written state in a separate file.
In a web application
In a servlet or JSP application, files under WEB-INF are not on the classpath, but the servlet context can read them, and they are never served to browsers:
try (InputStream in = getServletContext().getResourceAsStream("/WEB-INF/config.properties")) {
props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
}Files in WEB-INF/classes (where src/main/resources ends up) can use the class loader approach from earlier. Do this once at startup, in a ServletContextListener or the servlet's init, rather than on every request. In Spring Boot you would not read application.properties yourself at all: inject values with @Value or bind a group of them to a class with @ConfigurationProperties.
On Android: read from assets
Android has no classpath resources folder in the same sense, but files in src/main/assets/ are packaged into the APK as is and opened through AssetManager:
fun Context.loadProperties(name: String): Properties =
assets.open(name).bufferedReader(Charsets.UTF_8).use { reader ->
Properties().apply { load(reader) }
}
// in an Activity or Application
val config = loadProperties("config.properties")
val baseUrl = config.getProperty("api.base.url")use closes the reader even if load throws. Read the file once, for example in your Application class, and keep the values rather than reopening the asset on every screen.
Do not put API keys or other secrets in an assets file. An APK is a zip archive, and anyone can unpack it and read assets/config.properties in seconds. Moving the key into BuildConfig with a Gradle field makes it slightly less obvious, not secret. Keys that must stay private belong on your server, which the app calls with the user's own credentials.
For values that differ between debug and release builds, Gradle's buildConfigField or resource values per build type are usually a better fit than an assets file, because the compiler checks them.
Alternatives
Properties files are flat. When configuration grows nested sections or lists, YAML (with SnakeYAML or Jackson) or TOML read better, and frameworks such as Spring Boot accept either. For per-user application settings on the desktop, java.util.prefs.Preferences stores values in a platform-specific place without you managing a file.
If one of your properties is an encryption key, see the AES encryption tutorial for how to rebuild a key from its bytes, and why the key itself belongs in a secrets store rather than in this file. The class reference is java.util.Properties in the JDK documentation.