Explain Codes LogoExplain Codes Logo

How to use Java property files?

java
file-input-stream
properties-file
utf-8-encoding
Anton ShumikhinbyAnton Shumikhin·Dec 3, 2024
TLDR

Deploy Java property files pronto with the Properties class. Keep an eagle-eye on this essential snippet:

Properties props = new Properties(); try (InputStream input = new FileInputStream("config.properties")) { props.load(input); // Load properties from the file because reading is fun System.out.println(props.getProperty("key")); // Dear key, reveal your secret value! } catch (IOException e) { e.printStackTrace(); // Woops! An error has occurred, let's print it out and cry a little }

Your config.properties file should be shaped like:

key=value

And don't forget, IOException is managed and the input stream secures autoclosure thanks to try-with-resources.

Deal with divergent file locations and extensions

Although the usual is a .properties extension, maybe you dig .txt or custom extensions—Java doesn't blink. Store your file anywhere, but ensure the path in FileInputStream is correct or use Class.getResourceAsStream() to load from the classpath. For internationalization scenarios, ResourceBundle shines!

Loop over properties and exceptional property handling

Want to peek inside your property-file drawer? Iterate over the Properties object:

for (String key : props.stringPropertyNames()) { String value = props.getProperty(key); System.out.println(key + " = " + value); // Look, I found a key-value pair! 🕵️‍♀️ }

This sleuthing prints every key-value treasure in your configuration vault.

Keeping files UTF-8 friendly

For those sailing with Java 6 and dealing with non-ASCII characters in property files, sail the UTF-8 encoding seas:

try (Reader reader = new InputStreamReader(new FileInputStream("config.properties"), StandardCharsets.UTF_8)) { props.load(reader); // UTF-8 to the rescue! }

This small twist ensures every remote character Island is charted correctly.

Reaching for properties in JAR files

Sometimes properties are stashed in JAR files — here getResourceAsStream() saves the day:

try (InputStream input = ClassName.class.getResourceAsStream("/config.properties")) { props.load(input); // Jackpot! The property-laden JAR! }

Pro tip: the path starts with a slash when the file dwells at the root of the classpath paradise.

Catching property access exceptions

Always wrap your property file loading in try-catch — catching IO exceptions for unshakeable applications. A missing file shouldn't trigger a catastrophic cascade.

Packing properties files for comfort

Keep your properties files bundled in the same directory with the classes leveraging them for easy access and seamless maintenance. Cohesive file arrangement promotes development nirvana.