Skip to lesson

Properties files for settings

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

A program's folder name or error limit is written inside the code. Changing it means editing and recompiling, just for a small setting.

The key=value format

A properties file stores settings as key=value lines that a program can read with java.util.Properties, so values can change without changing code.

Each line of a .properties file is one setting: a key, then = (or :), then the value. Keys usually use dots to group related settings: db.url, db.user, report.folder. Lines starting with # or ! are comments, and blank lines are ignored.

Example 1 · What Properties makes of each line

PropertiesFormatDemo.javaJava
import java.io.IOException;import java.io.Reader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.Properties;
public class PropertiesFormatDemo {    static String show(String value) {        return value == null ? "null" : "[" + value.replace("\n", "<new line>") + "]";    }
    public static void main(String[] args) throws IOException {        Path file = Path.of("app.properties");        Files.write(file, List.of(                "# College app settings",                "app.name = Fest Portal",                "app.port: 8080",                "! another comment",                "student.name=Asha  ",                "data.dir=C:\\data\\new",                "data.dir.ok=C:/data/new",                "welcome=Hello,\\",                "        welcome to the fest"), StandardCharsets.UTF_8);
        System.out.println("The file:");        Files.readAllLines(file, StandardCharsets.UTF_8).forEach(l -> System.out.println("  " + l));
        Properties props = new Properties();        try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            props.load(in);        }        System.out.println("Settings loaded: " + props.size());        for (String key : List.of("app.name", "app.port", "student.name", "data.dir", "data.dir.ok", "welcome", "app.city")) {            System.out.println(key + " = " + show(props.getProperty(key)));        }        Files.deleteIfExists(file);    }}
Output
The file:
  # College app settings
  app.name = Fest Portal
  app.port: 8080
  ! another comment
  student.name=Asha
  data.dir=C:\data\new
  data.dir.ok=C:/data/new
  welcome=Hello,\
          welcome to the fest
Settings loaded: 6
app.name = [Fest Portal]
app.port = [8080]
student.name = [Asha  ]
data.dir = [C:data<new line>ew]
data.dir.ok = [C:/data/new]
welcome = [Hello,welcome to the fest]
app.city = null

What this code does

  • The comment lines are skipped, = and : both work, and the spaces after app.name = are dropped. The two spaces after Asha stay, as the brackets show.
  • In C:\data\new, the \d becomes d and \n becomes a new line, so the path is ruined; the forward-slash version is safe. The backslash at the end of the welcome line joins the next line, and its leading spaces are removed.

Spaces around the = and at the start of the value are removed, but spaces at the end of a value are kept. name=Asha gives "Asha " with two spaces, which can break a comparison much later. The backslash is special. \n means a new line, \t a tab, \\ one backslash, and a backslash at the end of a line joins it with the next line. So a Windows path like C:\data\new is read as C:data, a line break, and ew. Write C:\\data\\new or simply C:/data/new, which Java also accepts on Windows.

Loading with a UTF-8 Reader

props.load(reader) reads every setting from a Reader into a Properties object. Open the reader with Files.newBufferedReader(path, StandardCharsets.UTF_8) inside try-with-resources.

Example 2 · load(Reader) with UTF-8 versus load(InputStream)

Utf8PropertiesDemo.javaJava
import java.io.IOException;import java.io.InputStream;import java.io.Reader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.Properties;
public class Utf8PropertiesDemo {    public static void main(String[] args) throws IOException {        String hindi = "\u0928\u092E\u0938\u094D\u0924\u0947";      // "namaste" in Hindi, 6 characters        Path file = Path.of("messages.properties");        Files.writeString(file, "welcome=" + hindi + "\nfee.symbol=\u20B9\n", StandardCharsets.UTF_8);
        Properties wrong = new Properties();        try (InputStream in = Files.newInputStream(file)) {            wrong.load(in);                                        // reads bytes as ISO-8859-1        }        Properties right = new Properties();        try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            right.load(in);        }
        System.out.println("InputStream: length " + wrong.getProperty("welcome").length()                + ", correct = " + wrong.getProperty("welcome").equals(hindi));        System.out.println("UTF-8 Reader: length " + right.getProperty("welcome").length()                + ", correct = " + right.getProperty("welcome").equals(hindi));        System.out.println("Rupee sign correct: " + right.getProperty("fee.symbol").equals("\u20B9"));        Files.deleteIfExists(file);    }}
Output
InputStream: length 18, correct = false
UTF-8 Reader: length 6, correct = true
Rupee sign correct: true

What this code does

  • Each Hindi letter takes 3 bytes in UTF-8. load(InputStream) turns every byte into its own character, so the 6-letter word becomes 18 wrong characters.
  • load(Reader) with a UTF-8 reader decodes the bytes properly and gets the original word back. The program compares strings instead of printing them, because some terminals cannot show Hindi.

There is also load(InputStream), but it always reads the bytes as ISO-8859-1, an old Western European character set. A UTF-8 value such as a Hindi college name or the rupee sign comes out as junk. Use the Reader version, and the file can hold any language. A missing file throws NoSuchFileException. Decide what that means for your program: often it is fine to run with built-in defaults, and print one line saying so.

Old projects write non-English text in properties files as \u escapes, such as \u0928 for the Hindi letter na. That works with both load methods, but nobody can read the file. With a UTF-8 Reader you can write the text as it is.

getProperty with a default

props.getProperty(key) returns the value as a String, or null when the key is missing. props.getProperty(key, defaultValue) returns the default instead of null, so a missing setting never causes a NullPointerException.

Example 3 · Defaults and typed settings

TypedSettingsDemo.javaJava
import java.io.IOException;import java.io.StringReader;import java.util.Properties;
public class TypedSettingsDemo {    static int intSetting(Properties p, String key, int defaultValue) {        String text = p.getProperty(key);        if (text == null) {            return defaultValue;        }        try {            return Integer.parseInt(text.trim());        } catch (NumberFormatException e) {            throw new IllegalArgumentException("Setting " + key + " must be a whole number, but is '" + text + "'");        }    }
    static boolean boolSetting(Properties p, String key, boolean defaultValue) {        String text = p.getProperty(key);        return text == null ? defaultValue : Boolean.parseBoolean(text.trim());    }
    public static void main(String[] args) throws IOException {        Properties p = new Properties();        p.load(new StringReader("max.errors = 25 \nsend.email=TRUE\nreport.folder=reports\nretry.count=three\n"));
        System.out.println("folder: " + p.getProperty("report.folder"));        System.out.println("missing key: " + p.getProperty("report.title"));        System.out.println("with default: " + p.getProperty("report.title", "Monthly Report"));        System.out.println("max errors: " + intSetting(p, "max.errors", 10));        System.out.println("page size: " + intSetting(p, "page.size", 50));        System.out.println("send email: " + boolSetting(p, "send.email", false));        try {            intSetting(p, "retry.count", 3);        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }    }}
Output
folder: reports
missing key: null
with default: Monthly Report
max errors: 25
page size: 50
send email: true
Setting retry.count must be a whole number, but is 'three'

What this code does

  • getProperty gives null for a missing key; the two-argument version gives the default. intSetting also returns its default for page.size, which is not in the file.
  • max.errors has a trailing space, so trim() is needed before parseInt. Boolean.parseBoolean ignores case, so TRUE works. A bad number fails with a message that names the setting and shows its value.

Every value is text. For numbers and true/false settings, write small helpers such as intSetting(props, "max.errors", 10) that trim the value, convert it and, on bad input, throw an exception that names the key and the value. Put the defaults in the code, next to the helpers, so the program runs with no settings file at all. The file then only needs the settings that differ from the defaults.

Settings order: file, environment variable, system property

One setting can come from several places. An environment variable is a name and value set before the program starts, read with System.getenv("APP_PORT").

Terminal
java -Dapp.port=9090 SettingsDemo

A system property is passed with -D on the command line and read with System.getProperty("app.port").

On Windows

In PowerShell, set an environment variable with $env:NAME = "value". It applies to programs started from that window only.

Windows PowerShell
PS C:\Users\Priya\java-practice> $env:APP_PORT = "9091"PS C:\Users\Priya\java-practice> java SettingsDemo
In Command Prompt the same step is set APP_PORT=9091.

Example 4 · Layered settings: default, file, environment, -D

LayeredSettingsDemo.javaJava
import java.io.IOException;import java.io.StringReader;import java.util.Map;import java.util.Properties;
public class LayeredSettingsDemo {    static String setting(String key, String defaultValue, Properties file, Map<String, String> env) {        String fromSystem = System.getProperty(key);        if (fromSystem != null) {            return fromSystem + "   (system property)";        }        String envName = key.toUpperCase().replace('.', '_');        String fromEnv = env.get(envName);        if (fromEnv != null) {            return fromEnv + "   (environment " + envName + ")";        }        String fromFile = file.getProperty(key);        if (fromFile != null) {            return fromFile + "   (file)";        }        return defaultValue + "   (default)";    }
    public static void main(String[] args) throws IOException {        Properties file = new Properties();        file.load(new StringReader("app.port=8080\napp.city=Pune\nreport.folder=reports\n"));
        Map<String, String> env = Map.of("APP_PORT", "9091", "REPORT_FOLDER", "/srv/reports");        System.setProperty("app.port", "9090");          // same as starting with -Dapp.port=9090
        System.out.println("app.port      = " + setting("app.port", "80", file, env));        System.out.println("report.folder = " + setting("report.folder", "out", file, env));        System.out.println("app.city      = " + setting("app.city", "Delhi", file, env));        System.out.println("app.lang      = " + setting("app.lang", "en", file, env));    }}
Output
app.port      = 9090   (system property)
report.folder = /srv/reports   (environment REPORT_FOLDER)
app.city      = Pune   (file)
app.lang      = en   (default)

What this code does

  • setting checks the layers from strongest to weakest and stops at the first one that has a value. app.port is set in all three places, and the system property wins.
  • The environment is passed in as a Map so the demo gives the same output on every computer; a real program passes System.getenv(), which is also a Map<String, String>. System.setProperty stands in for typing -Dapp.port=9090.

A common order, also used by Spring Boot, goes from weakest to strongest. The built-in default comes first, the file overrides it, an environment variable overrides the file, and a -D system property overrides everything. The most specific choice, typed for this one run, wins.

Environment variable names cannot contain dots in most shells, so the usual rule is to write the key in capitals with underscores: app.port becomes APP_PORT.

Example 5 · An AppSettings record loaded from a file

AppSettingsDemo.javaJava
import java.io.IOException;import java.io.Reader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.Properties;
record AppSettings(String reportFolder, int maxErrors, boolean addBom) {    static AppSettings load(Path file) throws IOException {        Properties p = new Properties();        try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {            p.load(in);        } catch (NoSuchFileException e) {            System.out.println("No " + file.getFileName() + ", using defaults");        }        String folder = p.getProperty("report.folder", "reports").trim();        int maxErrors = Integer.parseInt(p.getProperty("import.max.errors", "10").trim());        if (maxErrors < 0) {            throw new IllegalArgumentException("import.max.errors cannot be negative: " + maxErrors);        }        boolean addBom = Boolean.parseBoolean(p.getProperty("csv.add.bom", "true").trim());        return new AppSettings(folder, maxErrors, addBom);    }}
public class AppSettingsDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("importer.properties");        Files.deleteIfExists(file);        System.out.println(AppSettings.load(file));
        Files.writeString(file, "# importer settings\nimport.max.errors=3\ncsv.add.bom=false\n", StandardCharsets.UTF_8);        System.out.println(AppSettings.load(file));        Files.deleteIfExists(file);    }}
Output
No importer.properties, using defaults
AppSettings[reportFolder=reports, maxErrors=10, addBom=true]
AppSettings[reportFolder=reports, maxErrors=3, addBom=false]

What this code does

  • All the reading, defaults and checks are in AppSettings.load. The rest of the program gets a record with typed fields and never touches Properties or text again.
  • With no file, every setting falls back to its default. With the file, the two settings it names are changed and report.folder keeps its default.

Next step

Check your understanding

12 quick questions