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 has been in Java since 1.0. It is a map of string keys to string values, with methods to read and write a simple line-based text format. Each line holds a key, a separator and a value; there are no sections, types, lists or nesting. Three design facts explain most of its surprises:

  • It extends Hashtable<Object, Object>. All methods are synchronized, and the inherited put accepts any object, even though the file format can only hold strings.
  • It can have a second Properties object as defaults. getProperty falls back to it, but the map methods (get, size, store) ignore it.
  • The original stream methods read and write ISO-8859-1, a one-byte-per-character charset, and escape everything else as \uXXXX. Methods that take a Reader or Writer came later and use whatever charset you choose.
Properties methods and when they arrived
MethodSinceNotes
load(InputStream), getPropertyJava 1.0Reads ISO-8859-1
setProperty, store(OutputStream, comment)Java 1.2Writes ISO-8859-1 with escapes
loadFromXML, storeToXMLJava 5XML format, UTF-8 by default
load(Reader), store(Writer, comment), stringPropertyNamesJava 6Any charset; names including defaults
Sorted output from store, java.properties.dateJava 18Reproducible files (JDK-8231640)

The format suits flat settings that people edit by hand: ports, names, feature flags, messages for ResourceBundle. It has no way to express a list or a nested structure except by naming conventions such as server.1.host, which is the point where YAML or JSON become the better choice. All programs below were compiled and run on JDK 21.

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.

Java
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:

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
.properties syntax as shown above
RuleExample lineValue read
Separator can be =, : or whitespace; spaces around it are ignoredapp.greeting Hello\tWorldHello, a tab, World
Lines starting with # or ! are comments! this is also a commentIgnored
A backslash is an escape, so a literal one is written twiceC:\\data\\inC:\data\in
A backslash at the end of a line continues it; leading spaces of the next line are droppedfirst part, \first part, second part
\uXXXX escapesZ\u00fcrichZürich
Nothing after the separatorempty.value =Empty string, not null
A repeated keyduplicate = ... twiceThe last one wins, silently

All values are strings. getProperty returns null for a missing key, or the default passed as its second argument, and numbers must be parsed by your code.

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 Hashtable API that Properties inherits.

Java
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:

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)
  • path.single = C:\data\in loaded as C:datain, because \d and \i are escapes of ordinary letters and the backslashes disappear without any error. Forward slashes, C:/data/in, avoid the problem and work on Windows too.
  • Trailing spaces are kept: the value ends with three spaces. A value such as 16 then fails Integer.parseInt, so strip values before parsing.
  • The first unescaped space ends the key. key with spaces = 1 created the key key with the value with spaces = 1. Spaces in keys must be escaped as \ .
  • A colon in a value is fine: only the first separator after the key counts, so the URL with :8443 survived.
  • config.put("port", 8080) compiled, because put takes Object. Then getProperty("port") returned null, since it ignores non-String values, stringPropertyNames left the key out, and store threw ClassCastException. Always use setProperty.

Defaults and store

A Properties object created with another one as its defaults falls back to them when a key is missing, which suits layered configuration: built-in values, overridden by a user file. The program stores the user layer to a file and loads it back. The city "Zürich" was chosen because it is not ASCII.

Java
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:

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
  • language came from the defaults. size() counts only the user's own 2 keys, while stringPropertyNames() includes the defaults and gives 4.
  • store 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, language is null: the defaults are not part of the file, so the code that reads it must set up the same defaults again.
  • With a Writer and Reader in UTF-8, "Zürich" was stored and read as it is.

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), then reads a UTF-8 file both ways and finishes with the XML format. It runs with -Djava.properties.date=2026-11-14, so the date comment is fixed.

Java
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:

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
  • store(OutputStream) escaped ü as \u00FC and € as \u20AC. The file is pure ASCII and loads correctly anywhere, but it is hard to edit by hand.
  • The keys came out sorted, alpha to zeta, although they were added in another order. Since Java 18, store writes entries in key order, and the system property java.properties.date 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.
  • A file saved as UTF-8 by an editor and read with load(InputStream) turned "Zürich" into "Zürich", because each of the two bytes of ü became its own ISO-8859-1 character. load(Reader) with UTF-8 read it correctly.
  • storeToXML writes UTF-8 by default, so non-ASCII text stays readable, and loadFromXML reads it back.

Note that ResourceBundle reads .properties files as UTF-8 since Java 9 (JEP 226), while Properties.load(InputStream) still reads ISO-8859-1. The same file can therefore look right in one and garbled in the other. Load through a Reader with an explicit charset.

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 -D system properties, so an operator can override any value without editing files. The program implements that order and validates a number. A fixed map stands in for System.getenv() so the output does not depend on the machine, and the program runs with -Dapp.mode=maintenance.

Java
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:

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: app.name from the defaults, app.threads from the file, app.port from the environment, which overrode the file's 9000, and app.mode from the system property.
  • Environment variable names usually cannot contain dots, so app.port maps to APP_PORT, the convention most frameworks follow.
  • The file's app.threads = 16 has a trailing space, visible as the extra space in the output. getInt strips it before parsing, then checks the range.
  • app.timeout=thirty 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.

System properties and environment variables

The JVM keeps its own Properties object of system properties. You add to it with -Dkey=value on the command line; this program was started with -Dapp.env=staging -Dapp.workers=8 -Dapp.debug=true.

Java
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:

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
  • Integer.getInteger and Boolean.getBoolean read system properties, not strings. The names are misleading: Boolean.getBoolean("true") is false unless a system property called true exists.
  • The JVM defines many properties itself, such as the Java version and the platform's separators. java.specification.version is 21 here because the program ran on JDK 21.
  • Environment variables are separate and read-only from Java, via System.getenv. APP_MODE was not set, so it is null.
  • System.setProperty changes the value for code that reads it afterwards, but many JDK settings are read once at startup. Setting stdout.encoding after the JVM has started, for example, does not change System.out. Pass such properties with -D.

Which approach to use

Choosing how to read and write properties
NeedUse
Read a properties fileload(Reader) with an explicit charset, usually UTF-8
Read a file bundled with the applicationgetResourceAsStream wrapped in an InputStreamReader; see classpath resources
Write a file people editstore(Writer) in UTF-8
Write a file that must be identical on every buildstore on Java 18 or later with -Djava.properties.date
Add or change a valuesetProperty, never put
Built-in fallback valuesnew Properties(defaults), remembering store leaves them out
Let operators override settingsDefaults, then file, then environment, then -D
Windows pathsForward slashes, or doubled backslashes
Lists, nesting or typesA richer format such as YAML, JSON or HOCON

Properties does not notice when its file changes. To reload configuration while the program runs, watch the file with a WatchService, load a fresh Properties object when the file is modified, and swap it in as a whole so readers never see a half-loaded mix.