How to read a .properties settings file
Short answer
Suppose there is a file app.properties — lines of the form key=value, comments start with #:
# server settings
server.port=8080
app.name=Coffee ShopThe Properties class reads such a file with load():
void main() throws IOException {
var props = new Properties();
try (var reader = Files.newBufferedReader(Path.of("app.properties"))) {
props.load(reader);
}
IO.println(props.getProperty("app.name"));
IO.println(props.getProperty("server.port"));
}Output:
Coffee Shop
8080Defaults and numbers
The second argument of getProperty() is the value used when the key is missing. Parse numbers with parseInt():
void main() throws IOException {
var props = new Properties();
try (var reader = Files.newBufferedReader(Path.of("app.properties"))) {
props.load(reader);
}
int port = Integer.parseInt(props.getProperty("server.port", "80"));
String mode = props.getProperty("app.mode", "production");
IO.println(port + 1);
IO.println(mode);
}Output:
8081
productionEnvironment variables
Secrets such as database passwords are better kept in environment variables rather than files. System.getenv() returns null if the variable is missing:
void main() {
String url = Objects.requireNonNullElse(System.getenv("MY_APP_DB_URL"), "jdbc:h2:mem:test");
IO.println(url);
}Output:
jdbc:h2:mem:testCommon mistake
Loading the file with props.load(InputStream). This version reads the file as ISO-8859-1, and non-Latin text turns into garbage. Pass a Reader from Files.newBufferedReader() — it reads UTF-8.
Functions used in this recipe
- BufferedReader — Reads text line by line with buffering — the classic way to process large files.
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.