How do I read and write data in Windows registry?

The java.util.prefs package provides a way for applications to store and retrieve user and system preferences and data configuration. These preference data will be stored persistently in an implementation-dependent backing stored. For example in Windows operating system in will stored in Windows registry.

To write and read these data we use the java.util.prefs.Preferences class. The following example will show you how to read and write to the HKCU and HKLM in the registry.

package org.kodejava.example.util.prefs;

import java.util.prefs.Preferences;

public class RegistryDemo {
    public static final String PREF_KEY = "org.kodejava";
    public static void main(String[] args) {
        // Write Preferences information to HKCU (HKEY_CURRENT_USER),
        // HKCUSoftwareJavaSoftPrefsorg.kodejava
        Preferences userPref = Preferences.userRoot();
        userPref.put(PREF_KEY, "");

        // Below we read back the value we've written in the code above.
        System.out.println("Preferences = "
                + userPref.get(PREF_KEY, PREF_KEY + " was not found."));

        // Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),
        // HKLMSoftwareJavaSoftPrefsorg.kodejava
        Preferences systemPref = Preferences.systemRoot();
        systemPref.put(PREF_KEY, "");

        // Read back the value we've written in the code above.
        System.out.println("Preferences = "
                + systemPref.get(PREF_KEY, PREF_KEY + " was not found."));

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.