views:

486

answers:

3

I need to access Windows registry from Java.. Also I need to copy some registry entries and may have to enter new registry variables using Java.. some one help me please...

+3  A: 

I'd recommend the Java Native Access (JNA) library. It's a pretty nice wrapper around JNI. According to this mailing list post, they've already got a contributed wrapper around the native Windows registry function calls.

If you add the JNA libraries to your project, the relevant source you'll want is the Registry.java class. From there, just call methods on that class to investigate the Windows registry.

As a side note, make sure when you use JNA that you use Platform.isXxx() to make sure your code can actually query the registry on the particular platform.

Martin
+2  A: 

An example will be like this:

import com.ice.jni.registry.*;

public class DeleteEnvironmentVar{
public DeleteEnvironmentVar(String variable, String value) throws Exception {

        RegistryKey machine = Registry.getTopLevelKey("HKEY_LOCAL_MACHINE");
        RegistryKey environment = machine.openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", RegistryKey.ACCESS_WRITE);
        try {
            if ( value == null ) { //Delete the variable in case value is empty
                environment.deleteValue(variable);
            }            
        }
        catch( NoSuchValueException nsve ) {}
        catch( NoSuchKeyException nske ) {}        
    }
}
Techmaddy
A: 

The Preferences class is the Java preferred way of writing to the registry. However, I haven't actually used it, so I don't know if it allows access to the entire registry or just a section specific to the JVM or your application. If it doesn't, then it sounds like for your purpose you'll be needing to look at the JNI solutions posited by others here. If it does work, then you have a platform-independent method of storing off your settings if you ever port it.

James
Only allows for a specific part unique for your application.
boutta
The fact that Preferences uses the Registry on Windows systems is just an implementation detail--Preferences is NOT a Registry API.
Alan Moore