Lesson 6 of 8
Working with Properties Files
Properties files (.properties) are the simplest configuration format in Java - key=value pairs per line. The Properties class reads them. Critical: never hardcode configuration (URLs, credentials, timeouts) in code. Load from properties files and differentiate dev vs prod environments.
Properties Files & Environment Separation
import java.io.*;
import java.nio.file.*;
import java.util.Properties;
// application-dev.properties:
// db.url=jdbc:postgresql://localhost:5432/library_dev
// db.user=dev_user
// db.password=dev123
// app.maxLoanDays=30
// log.level=DEBUG
// application-prod.properties:
// db.url=jdbc:postgresql://prod.server:5432/library
// db.user=prod_user
// db.password=${DB_PASS} ← use env var in prod
// app.maxLoanDays=14
// log.level=INFO
public class AppConfig {
private final Properties props;
// Load config based on active profile
public AppConfig() throws IOException {
String profile = System.getenv("APP_PROFILE"); // set in environment
if (profile == null) profile = "dev"; // default to dev
String fileName = "application-" + profile + ".properties";
Path configFile = Path.of("config", fileName);
props = new Properties();
// Load defaults first, then override with profile-specific
try (InputStream defaults = getClass().getResourceAsStream("/application.properties")) {
if (defaults != null) props.load(defaults);
}
if (Files.exists(configFile)) {
try (InputStream in = Files.newInputStream(configFile)) {
props.load(in); // profile values override defaults
}
} else {
System.err.println("Config file not found: " + configFile + " - using defaults");
}
System.out.println("Loaded profile: " + profile);
}
// Typed accessors
public String getDbUrl() { return getRequired("db.url"); }
public String getDbUser() { return getRequired("db.user"); }
public int getMaxLoanDays() {
return Integer.parseInt(props.getProperty("app.maxLoanDays", "14"));
}
public String getLogLevel() {
return props.getProperty("log.level", "INFO");
}
private String getRequired(String key) {
String val = props.getProperty(key);
if (val == null || val.isBlank())
throw new IllegalStateException("Required config missing: " + key);
// Resolve env variable references like ${DB_PASS}
if (val.startsWith("${") && val.endsWith("}")) {
String envKey = val.substring(2, val.length() - 1);
String envVal = System.getenv(envKey);
if (envVal == null)
throw new IllegalStateException("Env var not set: " + envKey);
return envVal;
}
return val;
}
// Write/update properties
public static void writeConfig(Path file, Properties config) throws IOException {
try (OutputStream out = Files.newOutputStream(file)) {
config.store(out, "Library Application Configuration");
}
}
}Config Profile Best Practices
- Never commit passwords or secrets to version control - use ${ENV_VAR} references in .properties files.
- application.properties = shared defaults; application-dev.properties = dev overrides; application-prod.properties = prod overrides.
- Load with getResourceAsStream for classpath resources (jar-bundled defaults) or Files.newInputStream for external configs.
- Log which config profile is loaded at startup - essential for debugging environment discrepancies.
- In production, consider environment variables or a Secret Manager (AWS Secrets Manager, HashiCorp Vault) instead of files.
Quick Quiz
Tip
Tip
Practice Working with Properties Files in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Working with Properties Files
Practice Task
Note
Practice Task - (1) Write a working example of Working with Properties Files from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Working with Properties Files is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Properties files (.
- Never commit passwords or secrets to version control - use ${ENV_VAR} references in .properties files.
- application.properties = shared defaults; application-dev.properties = dev overrides; application-prod.properties = prod overrides.
- Load with getResourceAsStream for classpath resources (jar-bundled defaults) or Files.newInputStream for external configs.
Finished this lesson?