java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to read / write data in Windows registry?

The Preferences class allows us to read and write information from the Windows registry. In this example we read and write to the HKCU and HKLM in the registry.

package com.javacoderanch.example.util;

import java.util.prefs.Preferences;

public class RegistryDemo {
    public static final String PREF_KEY = "com.javacoderanch";
    public static void main(String[] args) {
        //
        // Write Preferences information to HKCU (HKEY_CURRENT_USER),
        // HKCUSoftwareJavaSoftPrefscom.javacoderanch
        //
        Preferences userPref = Preferences.userRoot();
        userPref.put(PREF_KEY, "www.javacoderanch.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),
        // HKLMSoftwareJavaSoftPrefscom.javacoderanch
        //
        Preferences systemPref = Preferences.systemRoot();
        systemPref.put(PREF_KEY, "www.javacoderanch.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."));
    }
}