Reading and Writing Properties Files

Naveen AnamaneniUpdated · 3 min read

A properties file is a plain text file of key=value lines that stores configuration, such as a database URL or a theme setting. The Properties class itself was introduced in "Properties Class in Java"; this lesson focuses on the file side: loading a properties file from disk, changing values, saving it back, and supplying defaults when the file is missing. You will use NIO.2 readers and writers so the file is always read and written as UTF-8.

The Steps

StepCode
Loadprops.load(Files.newBufferedReader(path))
Read a valueprops.getProperty("key", "default")
Change a valueprops.setProperty("key", "value")
Saveprops.store(Files.newBufferedWriter(path), "comment")

Example: A Settings File with Defaults

Let's see an example that creates the settings file on first run and updates it on the second.

Settings.java▶ Try it
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
 
public class Settings {
    static final Path FILE = Path.of("app.properties");
 
    static Properties load() throws IOException {
        Properties defaults = new Properties();
        defaults.setProperty("theme", "light");
        defaults.setProperty("language", "en");
 
        Properties props = new Properties(defaults);
        if (Files.exists(FILE)) {
            try (Reader r = Files.newBufferedReader(FILE)) {
                props.load(r);
            }
        }
        return props;
    }
 
    static void save(Properties props) throws IOException {
        try (Writer w = Files.newBufferedWriter(FILE)) {
            props.store(w, "Settings for Navika");
        }
    }
 
    public static void main(String[] args) throws IOException {
        Properties first = load();
        System.out.println("First run theme: " + first.getProperty("theme"));
        first.setProperty("theme", "dark");
        save(first);
 
        Properties second = load();
        System.out.println("Second run theme: " + second.getProperty("theme"));
        System.out.println("Language (default): "
            + second.getProperty("language"));
 
        long settingLines = Files.readAllLines(FILE).stream()
            .filter(l -> !l.startsWith("#"))
            .count();
        System.out.println("Lines saved in the file: " + settingLines);
    }
}
Output
First run theme: light
Second run theme: dark
Language (default): en
Lines saved in the file: 1

Explanation: On the first load, no file exists, so every value comes from the defaults. Setting theme to dark and saving writes the file. On the second load, theme comes from the file, while language still comes from the defaults. Only the one changed setting is saved; store also writes two comment lines (the given comment and a timestamp).

Character Encoding

Common Mistakes

Loading a properties file through an InputStream when it contains non-English text. Use a UTF-8 Reader.

Expecting comments and order to survive store. store rewrites the file in its own format.

Crashing when the file is missing on first run. Check for it, or catch NoSuchFileException, and fall back to defaults.

Practice

  1. Easy: Store a user's name and favorite color in user.properties and print them on the next run.
  2. Harder: Count how many times a program has been run by storing a runs counter in a properties file.

Quick check: Properties files

4 questions
1Which method reads a properties file?
2Which method writes properties to a file?
3Why load with a Reader from Files.newBufferedReader?
4Where do values come from when a key isn't in the file?

Key Takeaways

Was this tutorial helpful?

Lesson 365 of 482