How do I read / 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, "www.kodejava.org");

        //
        // 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, "www.kodejava.org");

        //
        // 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

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply