Java: Read key from Windows Registry.

After create new windows registry in cmd by:
reg add HKLM\SOFTWARE\Policies\MyApplication\AES /v SecurityKey /d 12345678901234567890123456789012
need read it from java
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

public class WindowsReqistry {

    /**
     * 
     * @param location path in the registry
     * @param key registry key
     * @return registry value or null if not found
     */
    public static final String readRegistry(String location, String key){
        try {
            // Run reg query, then read output with StreamReader (internal class)
            Process process = Runtime.getRuntime().exec("reg query " + 
                    '"'+ location + "\" /v " + key);

            StreamReader reader = new StreamReader(process.getInputStream());
            reader.start();
            process.waitFor();
            reader.join();

            // Parse out the value
            String[] parsed = reader.getResult().split("\\s+");
            if (parsed.length > 1) {
                return parsed[parsed.length-1];
            }
        } catch (Exception e) {}

        return null;
    }

    static class StreamReader extends Thread {
        private InputStream is;
        private StringWriter sw= new StringWriter();

        public StreamReader(InputStream is) {
            this.is = is;
        }

        public void run() {
            try {
                int c;
                while ((c = is.read()) != -1)
                    sw.write(c);
            } catch (IOException e) { 
            }
        }

        public String getResult() {
            return sw.toString();
        }
    }
    public static void main(String[] args) {

        // Sample usage
        String value = WindowsReqistry.readRegistry("HKLM\\SOFTWARE\\Policies\\MyApplication\\AES", "SecurityKey");
        System.out.println(value);
    }
}

6 comments:

  1. Hi,

    The above code really works well for Windows related registry. But return null for other 3rd party registries.

    For example i am trying to get the "serviceName" of an application which returns null. If i try to get "ApplicationPath" then i am getting it.

    I appreciate if someone points me out the cause?

    ReplyDelete
  2. This looks great but I have a question, I'm trying to display the entire path for the key and save it in a txt file, but I'm not quite sure how I can do that? If you'd suggest anything please email me or just mention me so that I know I got a reply, thank you

    ReplyDelete
  3. this program is not working for me anymore

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete