2008-11-25

Using Windows registry with Java

Needed a way to store (and retrieve) strings on a local host from a Java application. Found some JNI-ways but that didn't feel "pure". Solution was java.util.prefs as in:


import java.util.prefs.*;

public class Main {
static Preferences prefs;

public static void main(String[] args) {

prefs = Preferences.userRoot();
String Installed = "";
String Name = "";
String def = "NA";

try {
Installed = prefs.get("Installed", def);
Name = prefs.get("Name", def);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("Installed: " + Installed);
System.out.println("Name: " + Name);

if(Installed.equalsIgnoreCase("NA")) {
prefs.put("Installed", new java.util.Date().toString());
prefs.put("Name", "jonas testar");
}

System.out.println("Date: " + new java.util.Date().toString());
}
}


Quite easy when one know how to do it.

prefs = Preferences.userRoot(); means that we are using HKEY_CURRENT_USER tree in registry. userRoot() can be changed to systemRoot()..