Wednesday, December 22, 2010

How to Read Windows Registry Keys, Key values using JAVA?


How to Read Windows Registry Keys, Key values using JAVA?

 public String regread(String query1)
{
             Process process = Runtime.getRuntime().exec(query1);
            StreamReader reader1 = new StreamReader(process.getInputStream());
            reader1.start();
            process.waitFor();
            reader1.join();
            String output = reader1.getResult();           
            return output;
}
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();
        }
    }

you can put this code as seperate class. You can pass the query to this function it will return the output.

What is that Query?

Before that  exec method is very important. exec method is used to execute the given string in the command prompt and get the output from the command prompt. so whatever you can do in command prompt as well as you can do in JAVA also.

Query for reading registry is :
reg query \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\"  /v \"classpath\"

Above query is used to read the classpath in environmental variables. this query only read the exact value in the registry.

dont put same query in cmd error will come.type this in cmd : reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"  /v "classpath"



If you want to read all subkeys in the registry?

reg query \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\"  /s

i think its very useful for you. if you need more above this give comments.

No comments:

Post a Comment