Properties files in Java
A .properties file is Java's traditional configuration format: one key and value per line. The java.util.Properties class reads and writes it, but the format has more rules than it appears to, its stream methods use ISO-8859-1, and the class itself is an old Hashtable that accepts values it cannot store. This page tests each rule and trap, then builds layered configuration with validation.
Contents
How Properties works
java.util.Properties
- It extends
. All methods are synchronized, and the inheritedHashtable<Object, Object> accepts any object, even though the file format can only hold strings.put - It can have a second
object as defaults.Properties falls back to it, but the map methods (getProperty ,get ,size ) ignore it.store - The original stream methods read and write ISO-8859-1, a one-byte-per-character charset, and escape everything else as
. Methods that take a\uXXXX orReader came later and use whatever charset you choose.Writer
| Method | Since | Notes |
|---|---|---|
load(InputStream)getProperty | Java 1.0 | Reads ISO-8859-1 |
setPropertystore(OutputStream, comment) | Java 1.2 | Writes ISO-8859-1 with escapes |
loadFromXMLstoreToXML | Java 5 | XML format, UTF-8 by default |
load(Reader)store(Writer, comment)stringPropertyNames | Java 6 | Any charset; names including defaults |
Sorted output from storejava.properties.date | Java 18 | Reproducible files (JDK-8231640) |
The format suits flat settings that people edit by hand: ports, names, feature flags, messages for ResourceBundleserver.1.host
The format, rule by rule
The program loads a small properties text that uses every syntax rule once, then prints what each key really contains. Brackets around the values make leading and trailing spaces visible.
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import java.util.TreeMap;
public class PropertiesFormat {
public static void main(String[] args) throws IOException {
String file = """
# Comments start with # or !
! this is also a comment
app.name = Demo Shop
app.port:8080
app.greeting Hello\\tWorld
path.windows = C:\\\\data\\\\in
multi.line = first part, \\
second part
unicode = Z\\u00fcrich
empty.value =
duplicate = first
duplicate = second
""";
Properties p = new Properties();
p.load(new StringReader(file));
// TreeMap only to print the keys in a stable order
// (tabs are printed as \t so they are visible)
new TreeMap<>(p).forEach((k, v) -> System.out.printf("%-14s = [%s]%n", k,
v.toString().replace("\t", "\\t")));
// getProperty returns null for missing keys, or the default you pass
System.out.println("missing key: " + p.getProperty("app.timeout"));
System.out.println("missing with default: " + p.getProperty("app.timeout", "30"));
// Everything is a String: convert and validate yourself
int port = Integer.parseInt(p.getProperty("app.port"));
System.out.println("port + 1 = " + (port + 1));
}
}
Output:
app.greeting = [Hello\tWorld]
app.name = [Demo Shop]
app.port = [8080]
duplicate = [second]
empty.value = []
multi.line = [first part, second part]
path.windows = [C:\data\in]
unicode = [Zürich]
missing key: null
missing with default: 30
port + 1 = 8081
| Rule | Example line | Value read |
|---|---|---|
Separator can be =: | app.greeting Hello\tWorld | HelloWorld |
Lines starting with #! | ! this is also a comment | Ignored |
| A backslash is an escape, so a literal one is written twice | C:\\data\\in | C:\data\in |
| A backslash at the end of a line continues it; leading spaces of the next line are dropped | first part, \ | first part, second part |
\uXXXX | Z\u00fcrich | Zürich |
| Nothing after the separator | empty.value = | Empty string, not null |
| A repeated key | duplicate = ... | The last one wins, silently |
All values are strings. getPropertynull
Traps: backslashes, spaces and non-String values
The next program loads lines that look reasonable but do not mean what they seem, and then misuses the HashtableProperties
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Properties;
public class FormatTraps {
public static void main(String[] args) throws IOException {
Properties p = new Properties();
p.load(new StringReader("""
path.single = C:\\data\\in
path.slash = C:/data/in
trailing = value with spaces after it \s
key with spaces = 1
key\\ with\\ escaped\\ spaces = 2
url = https://example.com:8443/api
"""));
System.out.println("path.single = [" + p.getProperty("path.single") + "]");
System.out.println("path.slash = [" + p.getProperty("path.slash") + "]");
System.out.println("trailing = [" + p.getProperty("trailing") + "]");
System.out.println("\"key\" = [" + p.getProperty("key") + "]");
System.out.println("\"key with escaped spaces\" = ["
+ p.getProperty("key with escaped spaces") + "]");
System.out.println("url = [" + p.getProperty("url") + "]");
// Properties extends Hashtable<Object, Object>, so non-String values slip in
Properties config = new Properties();
config.put("port", 8080); // compiles: put takes Object
config.setProperty("host", "localhost");
System.out.println("get(\"port\"): " + config.get("port"));
System.out.println("getProperty(\"port\"): " + config.getProperty("port"));
System.out.println("stringPropertyNames: " + config.stringPropertyNames());
try {
config.store(new StringWriter(), null);
} catch (ClassCastException e) {
System.out.println("store: ClassCastException (Integer is not a String)");
}
}
}
Output:
path.single = [C:datain]
path.slash = [C:/data/in]
trailing = [value with spaces after it ]
"key" = [with spaces = 1]
"key with escaped spaces" = [2]
url = [https://example.com:8443/api]
get("port"): 8080
getProperty("port"): null
stringPropertyNames: [host]
store: ClassCastException (Integer is not a String)
loaded aspath.single = C:\data\in , becauseC:datain and\d are escapes of ordinary letters and the backslashes disappear without any error. Forward slashes,\i , avoid the problem and work on Windows too.C:/data/in- Trailing spaces are kept: the value ends with three spaces. A value such as
then fails16 , so strip values before parsing.Integer.parseInt - The first unescaped space ends the key.
created the keykey with spaces = 1 with the valuekey . Spaces in keys must be escaped aswith spaces = 1 .\ - A colon in a value is fine: only the first separator after the key counts, so the URL with
survived.:8443 compiled, becauseconfig.put("port", 8080) takesput . ThenObject returnedgetProperty("port") , since it ignores non-String values,null left the key out, andstringPropertyNames threwstore . Always useClassCastException .setProperty
Defaults and store
A Properties
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
public class StoreAndDefaults {
public static void main(String[] args) throws IOException {
// Layered configuration: built-in defaults, overridden by a user file
Properties defaults = new Properties();
defaults.setProperty("theme", "light");
defaults.setProperty("language", "en");
defaults.setProperty("autosave", "true");
Properties user = new Properties(defaults); // falls back to defaults
user.setProperty("theme", "dark");
user.setProperty("city", "Zürich");
System.out.println("theme: " + user.getProperty("theme"));
System.out.println("language: " + user.getProperty("language"));
System.out.println("own keys: " + user.size() + ", visible names: "
+ user.stringPropertyNames().size());
// store writes only the user's own keys, plus a comment and a date line
Path file = Files.createTempFile("settings", ".properties");
try (Writer w = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
user.store(w, "User settings");
}
System.out.println("--- file content (date line removed) ---");
Files.readAllLines(file).stream().filter(l -> !l.startsWith("#") || l.contains("User"))
.sorted().forEach(System.out::println);
// Read it back with the same charset
Properties loaded = new Properties();
try (Reader r = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
loaded.load(r);
}
System.out.println("--- loaded back ---");
System.out.println("city: " + loaded.getProperty("city") + ", theme: "
+ loaded.getProperty("theme") + ", language: " + loaded.getProperty("language"));
Files.delete(file);
}
}
Output:
theme: dark
language: en
own keys: 2, visible names: 4
--- file content (date line removed) ---
#User settings
city=Zürich
theme=dark
--- loaded back ---
city: Zürich, theme: dark, language: null
came from the defaults.language counts only the user's own 2 keys, whilesize() includes the defaults and gives 4.stringPropertyNames() wrote only the own keys, a comment line, and a date line, filtered out above because it changes on every run. After loading the file back,store islanguage : the defaults are not part of the file, so the code that reads it must set up the same defaults again.null- With a
andWriter in UTF-8, "Zürich" was stored and read as it is.Reader
ISO-8859-1, UTF-8, sorted output and XML
Encoding is where properties files break most often, because the oldest methods are still the most used. The program writes four keys in a scrambled order with store(OutputStream)-Djava.properties.date=2026-11-14
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public class EncodingAndOrder {
public static void main(String[] args) throws IOException {
Properties p = new Properties();
p.setProperty("zeta", "last");
p.setProperty("city", "Zürich");
p.setProperty("alpha", "first");
p.setProperty("price", "5 €");
// store(OutputStream) writes ISO-8859-1 and escapes everything else
ByteArrayOutputStream latin1 = new ByteArrayOutputStream();
p.store(latin1, "written with store(OutputStream)");
System.out.print(latin1.toString(StandardCharsets.ISO_8859_1));
// A UTF-8 file read with load(InputStream) comes back garbled
byte[] utf8File = "city=Zürich\n".getBytes(StandardCharsets.UTF_8);
Properties wrong = new Properties();
wrong.load(new ByteArrayInputStream(utf8File));
Properties right = new Properties();
right.load(new InputStreamReader(new ByteArrayInputStream(utf8File),
StandardCharsets.UTF_8));
System.out.println("UTF-8 file via load(InputStream): " + wrong.getProperty("city"));
System.out.println("UTF-8 file via load(Reader): " + right.getProperty("city"));
// The XML format is UTF-8 by default
ByteArrayOutputStream xml = new ByteArrayOutputStream();
Properties small = new Properties();
small.setProperty("city", "Zürich");
small.storeToXML(xml, null);
System.out.print(xml.toString(StandardCharsets.UTF_8));
Properties fromXml = new Properties();
fromXml.loadFromXML(new ByteArrayInputStream(xml.toByteArray()));
System.out.println("loadFromXML: " + fromXml.getProperty("city"));
}
}
Output:
#written with store(OutputStream)
#2026-11-14
alpha=first
city=Z\u00FCrich
price=5 \u20AC
zeta=last
UTF-8 file via load(InputStream): Zürich
UTF-8 file via load(Reader): Zürich
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="city">Zürich</entry>
</properties>
loadFromXML: Zürich
escapedstore(OutputStream) asü and\u00FC as€ . The file is pure ASCII and loads correctly anywhere, but it is hard to edit by hand.\u20AC- The keys came out sorted, alpha to zeta, although they were added in another order. Since Java 18,
writes entries in key order, and the system propertystore replaces the timestamp comment. Together they make the file identical on every build, which matters for reproducible builds and version control. Before Java 18 the order followed the hash table.java.properties.date - A file saved as UTF-8 by an editor and read with
turned "Zürich" into "Zürich", because each of the two bytes ofload(InputStream) became its own ISO-8859-1 character.ü with UTF-8 read it correctly.load(Reader) writes UTF-8 by default, so non-ASCII text stays readable, andstoreToXML reads it back.loadFromXML
Note that ResourceBundle.propertiesProperties.load(InputStream)Reader
Layered configuration with validation
Real applications rarely read one file. A common order, from lowest to highest priority, is built-in defaults, a properties file, environment variables and -DSystem.getenv()-Dapp.mode=maintenance
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;
public class LayeredConfig {
// Lowest to highest priority: built-in defaults, file, environment, -D system property
static final class Config {
private final Properties file;
private final Map<String, String> env;
Config(Properties file, Map<String, String> env) {
this.file = file;
this.env = env;
}
String get(String key) {
String sys = System.getProperty(key);
if (sys != null) {
return sys + " (system property)";
}
String envName = key.toUpperCase().replace('.', '_'); // app.port -> APP_PORT
if (env.containsKey(envName)) {
return env.get(envName) + " (environment " + envName + ")";
}
String value = file.getProperty(key);
return value == null ? null : value + (file.containsKey(key)
? " (file)" : " (default)");
}
int getInt(String key, int min, int max) {
String raw = System.getProperty(key, env.getOrDefault(
key.toUpperCase().replace('.', '_'), file.getProperty(key)));
int value;
try {
value = Integer.parseInt(raw.strip());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(key + " is not a number: \"" + raw + "\"");
}
if (value < min || value > max) {
throw new IllegalArgumentException(key + "=" + value + " outside " + min + ".."
+ max);
}
return value;
}
}
public static void main(String[] args) throws IOException {
Properties defaults = new Properties();
defaults.setProperty("app.port", "8080");
defaults.setProperty("app.threads", "4");
defaults.setProperty("app.name", "shop");
defaults.setProperty("app.timeout", "30");
Properties file = new Properties(defaults);
file.load(new StringReader("app.port=9000\napp.threads = 16 \napp.timeout=thirty\n"));
// Stand-in for System.getenv(), so the output does not depend on the machine
Map<String, String> env = Map.of("APP_PORT", "9100");
Config c = new Config(file, env);
for (String key : new String[] {"app.name", "app.threads", "app.port", "app.mode"}) {
System.out.printf("%-12s = %s%n", key, c.get(key));
}
System.out.println("app.threads as int: " + c.getInt("app.threads", 1, 64));
try {
c.getInt("app.timeout", 1, 600);
} catch (IllegalArgumentException e) {
System.out.println("validation: " + e.getMessage());
}
}
}
Output:
app.name = shop (default)
app.threads = 16 (file)
app.port = 9100 (environment APP_PORT)
app.mode = maintenance (system property)
app.threads as int: 16
validation: app.timeout is not a number: "thirty"
- Each key reports where its value came from:
from the defaults,app.name from the file,app.threads from the environment, which overrode the file's 9000, andapp.port from the system property.app.mode - Environment variable names usually cannot contain dots, so
maps toapp.port , the convention most frameworks follow.APP_PORT - The file's
has a trailing space, visible as the extra space in the output.app.threads = 16 strips it before parsing, then checks the range.getInt failed with a message that names the key and the value. A configuration object like this one is also the right place to keep the parsed values, so the rest of the program never sees raw strings. Validating everything at startup, rather than when the value is first used, turns a bad deployment into an immediate, clear error.app.timeout=thirty
System properties and environment variables
The JVM keeps its own Properties-Dkey=value-Dapp.env=staging -Dapp.workers=8 -Dapp.debug=true
public class SystemProps {
public static void main(String[] args) {
// Set with -Dkey=value on the command line; read with System.getProperty
System.out.println("app.env (from -D): " + System.getProperty("app.env"));
System.out.println("app.region (not set): " + System.getProperty("app.region", "eu"));
System.out.println("Integer.getInteger: " + Integer.getInteger("app.workers", 4));
System.out.println("Boolean.getBoolean: " + Boolean.getBoolean("app.debug"));
// A few properties every JVM defines
System.out.println("java.specification.version: "
+ System.getProperty("java.specification.version"));
System.out.println("file.separator: " + System.getProperty("file.separator"));
System.out.println("line.separator escaped: "
+ System.getProperty("line.separator").replace("\n", "\\n").replace("\r", "\\r"));
// Environment variables are a separate, read-only mechanism
System.out.println("APP_MODE env var: " + System.getenv("APP_MODE"));
}
}
Output:
app.env (from -D): staging
app.region (not set): eu
Integer.getInteger: 8
Boolean.getBoolean: true
java.specification.version: 21
file.separator: /
line.separator escaped: \n
APP_MODE env var: null
andInteger.getInteger read system properties, not strings. The names are misleading:Boolean.getBoolean isBoolean.getBoolean("true") unless a system property calledfalse exists.true- The JVM defines many properties itself, such as the Java version and the platform's separators.
is 21 here because the program ran on JDK 21.java.specification.version - Environment variables are separate and read-only from Java, via
.System.getenv was not set, so it isAPP_MODE .null changes the value for code that reads it afterwards, but many JDK settings are read once at startup. SettingSystem.setProperty after the JVM has started, for example, does not changestdout.encoding . Pass such properties withSystem.out .-D
Which approach to use
| Need | Use |
|---|---|
| Read a properties file | load(Reader) |
| Read a file bundled with the application | getResourceAsStreamInputStreamReader |
| Write a file people edit | store(Writer) |
| Write a file that must be identical on every build | store-Djava.properties.date |
| Add or change a value | setPropertyput |
| Built-in fallback values | new Properties(defaults)store |
| Let operators override settings | Defaults, then file, then environment, then -D |
| Windows paths | Forward slashes, or doubled backslashes |
| Lists, nesting or types | A richer format such as YAML, JSON or HOCON |
PropertiesProperties