Friday, 26 September 2014

Read Registry Value Using Java - Get Oracle Home From Regedit In Java

import java.io.*;

public class RegQuery {


    public static String executeRegistryQuery(String query, String regToke) {
        try {
            Process process = Runtime.getRuntime().exec(query);
            StreamReader reader = new StreamReader(process.getInputStream());

            reader.start();
            process.waitFor();
            reader.join();

            String result = reader.getResult();
            int p = result.indexOf(regToke);

            if (p == -1)
                return null;

            return result.substring(p + regToke.length()).trim();
        }
        catch (Exception e) {
            return null;
        }
    }


    static class StreamReader extends Thread {
        private InputStream is;
        private StringWriter sw;

        StreamReader(InputStream is) {
            this.is = is;
            sw = new StringWriter();
        }

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

        String getResult() {
            return sw.toString();
        }
    }

    public static void main(String s[]) {

        String REGQUERY_UTIL = "reg query ";
        String REGDWORD_TOKEN = "REG_DWORD";

        String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
                "\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
                + "Explorer\\Shell Folders\" /v Personal";
        String CPU_SPEED_CMD = REGQUERY_UTIL +
                "\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
                + " /v ~MHz";
        String CPU_NAME_CMD = REGQUERY_UTIL +
                "\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
                + " /v ProcessorNameString";

        String REGSTR_TOKEN = "REG_SZ";
        String key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\ORACLE\\KEY_OraDb11g_home1";
        String value = "ORACLE_HOME";
        String executeString =    REGQUERY_UTIL + "\"" + key + "\"" + " /v " + value;


        System.out.println("Query Result : "
                + executeRegistryQuery(executeString, REGSTR_TOKEN));
        System.out.println("Query Result : "
                + executeRegistryQuery(PERSONAL_FOLDER_CMD, REGSTR_TOKEN));
        System.out.println("Query Result : "
                + executeRegistryQuery(CPU_SPEED_CMD, REGDWORD_TOKEN));
        System.out.println("Query Result : "
                + executeRegistryQuery(CPU_NAME_CMD, REGSTR_TOKEN));
    }
}

No comments:

Post a Comment