Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 201 ยท Input and Output

Properties Files and Configuration

Learn Java configuration - load and store .properties files with java.util.Properties, defaults, system properties with -D, environment variables and Preferences.

Almost every real program has settings that change between machines: a port number, a database URL, a log level, a feature switch. Hard-coding them means recompiling for every environment. Instead, you keep them outside the code and read them at startup.

Java's built-in tool for this is java.util.Properties, a map of string keys to string values that can read and write the simple .properties text format. This lesson covers that format in detail, then the two other places configuration comes from, system properties (-Dname=value) and environment variables, and finishes with a small pattern that combines all three the way production apps do.

The .properties format

A properties file is plain text with one key=value pair per line:

PROPERTIES
# Settings for the order service
app.name=Order Service
server.port=8080
server.host = 0.0.0.0
feature.discounts: true
greeting Hello there

The rules are short but have a few surprises:

  • Lines starting with # or ! are comments. Blank lines are ignored.
  • The separator can be =, : or just whitespace. Spaces around the separator are dropped, so server.host = 0.0.0.0 gives the value 0.0.0.0.
  • Trailing spaces in a value are kept. They're invisible in an editor and a classic source of "the port is not a number" bugs.
  • A backslash at the end of a line continues the value on the next line; leading spaces on the continuation are skipped.
  • Backslash escapes work as in Java strings: \t, \n, \\, and \uXXXX. To put =, :, # or a space inside a key, escape it with \.
  • Keys are case-sensitive. If a key appears twice, the last one wins.
  • Everything is a string. 8080 is the text "8080" until you parse it.

Dotted names like server.port are only a convention for grouping; the format has no real sections or nesting.

Loading properties

Properties.load(Reader) parses the format. Real code reads a file, but any Reader works, so this example loads from a text block with a StringReader:

Java Loading properties from text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The double backslashes (\\n, \\ at line ends) are there because the text sits inside a Java text block; in a real .properties file you would write a single \. Notice that app.name was defined twice and the second value won, and that the continuation lines of long.list were joined into one value.

The methods you'll use most:

Method Does
load(Reader) / load(InputStream) parse the .properties format and add the pairs
getProperty(key) the value, or null if missing
getProperty(key, default) the value, or default if missing
setProperty(key, value) add or replace a pair
stringPropertyNames() the keys (including those from defaults) as a Set<String>
store(Writer, comment) write the pairs back in .properties format
loadFromXML / storeToXML the same data in an XML format

load(InputStream) decodes bytes as ISO-8859-1 (Latin-1), not UTF-8, for historical reasons. A file containing cafรฉ or โ‚ฌ saved as UTF-8 turns into garbage. Always load through a Reader with an explicit charset, such as Files.newBufferedReader(path) (UTF-8 by default) or new InputStreamReader(in, StandardCharsets.UTF_8). See Character Sets and Encoding for why this matters.

Reading and writing a file

Here is the full round trip with a real file: write a config file, load it, change a value and save it again with store. Files created in our editor exist only while the program runs, so the example creates its own file first.

Java Load, change and store a config file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the saved file and you'll notice three things:

  • store writes your comment, then a timestamp comment (# plus the current date), then the pairs. The date changes every run, which makes stored files awkward to diff in version control. Since Java 18 you can replace it by starting the JVM with -Djava.properties.date="any fixed text".
  • The original comments and order are gone. Since Java 18, store writes the pairs sorted by key; older versions used hash order. Properties is a map: it only remembers keys and values. If humans edit the file, treat it as read-only input and don't rewrite it with store.
  • With a Writer, non-ASCII text like โ‚ฌ is written as is. store(OutputStream, ...) would instead write every character above ~ as an escape (โ‚ฌ becomes โ‚ฌ, รฉ becomes รฉ), which keeps the file pure ASCII.

Inside a packaged application, a default config file usually ships in the JAR (for example in src/main/resources). Read it from the classpath with Main.class.getResourceAsStream("/app.properties"), wrapped in an InputStreamReader with UTF-8. Check for null: it means the resource wasn't found.

Defaults and typed values

A Properties object can be created with another Properties object as its defaults. When a key is missing, getProperty looks it up in the defaults. That gives you a clean layering of "built-in values" under "user values" without copying anything.

Because every value is a string, you'll also want small helpers that parse numbers and booleans and fail with a clear message:

Java Defaults and typed getters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Validate configuration once, at startup, and stop with a precise message if something is wrong. A program that starts with a broken setting and fails an hour later, deep inside a request, is much harder to fix. Note also that Boolean.parseBoolean never fails: anything except "true" (ignoring case) is false, including the typo "ture". Strict code checks for exactly true or false.

For historical reasons Properties extends Hashtable<Object, Object>, so it also has put, get and entrySet. Don't use them. put("port", 8080) stores an Integer, which getProperty then ignores (it returns null for non-string values) and store rejects with a ClassCastException. Stick to setProperty and getProperty. And get doesn't consult the defaults; getProperty does.

System properties

The JVM keeps its own Properties object, the system properties. Some are always set by the JVM itself, and you can add your own on the command line with -D:

Terminal
java -Dapp.env=staging -Dserver.port=9000 -jar orders.jar
Java Reading and setting system properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Useful built-in keys include java.version, java.home, os.name, os.arch, user.name, user.home, user.dir (the working directory), line.separator, file.separator and java.io.tmpdir. For the separators you'll usually prefer System.lineSeparator() and Path, which handle them for you.

Integer.getInteger(name) and Boolean.getBoolean(name) read a system property with that name. They don't parse the string you pass in. Boolean.getBoolean("true") looks for a property called true and returns false. To parse text, use Integer.parseInt and Boolean.parseBoolean.

System properties are global to the whole JVM, so changing them at runtime affects every library that reads them. Treat System.setProperty as something for tests and startup code only.

Environment variables

Environment variables come from the operating system, and they're the standard way to configure apps in containers and cloud platforms (the "twelve-factor" style). Read them with System.getenv:

Java Reading environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Key facts:

  • System.getenv(name) returns null when the variable isn't set. On Windows names are case-insensitive; on Linux and macOS they're case-sensitive.
  • The map from System.getenv() is unmodifiable. A Java program can't change its own environment; you set variables before starting it, or pass them to child processes through ProcessBuilder.environment().
  • By convention environment variables use UPPER_SNAKE_CASE (DATABASE_URL), while properties use lower.dotted.names (database.url).
  • Secrets such as passwords and API keys belong in environment variables or a secrets manager, never in a properties file committed to Git. Don't print them in logs either.

Putting it together: layered configuration

Production frameworks resolve each setting from several sources, with a clear priority. A common order, from lowest to highest: built-in defaults, then the config file, then environment variables, then -D system properties. Each layer overrides the one before. Here is a compact version of that idea:

Java A layered config lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

server.port comes from the system property, log.level from the environment, db.url from the file and cache.ttl from the default. Passing the environment in as a Map instead of calling System.getenv() inside the class also makes the code easy to test. Spring Boot and similar frameworks do essentially this, with many more layers (Advanced Java).

Preferences and other formats

Two more options are worth knowing about:

  • java.util.prefs.Preferences stores small per-user or system-wide settings for desktop apps (window size, last opened folder) in a platform-specific place: the registry on Windows, files under the home directory elsewhere. You don't choose the file; Java does.
Java
import java.util.prefs.Preferences;

Preferences prefs = Preferences.userNodeForPackage(Main.class);
prefs.putInt("window.width", 1280);
int width = prefs.getInt("window.width", 800);   // 800 if never saved
  • YAML, JSON and TOML files can express nesting and lists, which .properties can't. Java has no built-in parser for them; libraries such as Jackson or SnakeYAML read them. Frameworks like Spring Boot accept both application.properties and application.yml.

For plain key-value settings, .properties remains perfectly fine, and it needs no dependencies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A properties file contains port = 8080 and later port=9090. What does getProperty("port") return?

    Duplicate keys are allowed and the last one read wins. The spaces around = are dropped, but the value is still a String.
  2. 2. What does Boolean.getBoolean("true") return when no system property named "true" exists?

    Boolean.getBoolean reads the system property with the given name. There is no property called "true", so it returns false. Use Boolean.parseBoolean to parse a string.
  3. 3. You load a UTF-8 file containing "cafรฉ" with props.load(new FileInputStream(file)). What happens?

    load(InputStream) always decodes as Latin-1, so the two UTF-8 bytes of รฉ become two wrong characters. Load through a Reader with UTF-8, for example Files.newBufferedReader(path).
  4. 4. Properties p = new Properties(defaults); where defaults has key "a". What do p.getProperty("a") and p.size() return if p itself is empty?

    getProperty falls back to the defaults, but the defaults are not copied into p, so size() (a Hashtable method) still counts only p's own entries.
  5. 5. Why should an API key not go into application.properties inside your Git repository?

    Committed files are copied to every clone and stay in Git history even after deletion. Inject secrets at runtime through the environment or a dedicated secrets store.

Summary

  • java.util.Properties maps string keys to string values and reads and writes the .properties format (key=value, # comments, \ continuations, escapes).
  • Use getProperty(key, default) and setProperty; never put/get, which bypass string handling and defaults.
  • Load files through a UTF-8 Reader; load(InputStream) assumes Latin-1. store drops comments and adds a timestamp.
  • new Properties(defaults) layers built-in values under user values; parse and validate typed values once at startup.
  • System properties come from the JVM and -Dkey=value; Integer.getInteger and Boolean.getBoolean read properties, not strings.
  • Environment variables (System.getenv) are read-only from Java and are the right home for secrets and container settings.
  • Real apps resolve settings in layers: defaults, file, environment, system properties.

Next: Compressing Data with GZIP and ZIP, where you'll shrink data and build ZIP archives entirely in memory.