Wednesday, October 30, 2013

Reading windows registry using Runtime.getRuntime().exec(..) command

In my previous post @ http://exploreeclipse.blogspot.in/2013/10/reading-windows-registry-values-using.html , I was talked about reading windows registry using JNA library. But Java also provides support to read the windows registry through Java Runtime command execution.

In this article will focus on how to read win registry using Runtime.getRuntime().exec(..) command.

Basically you need these 3 parameters to hit the registry.
1. What is the Location ?
2. What is the registry key type ?
3. What is the key you want to read ?

Example:
I want to read the following parameters.
Location = "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Android SDK Tools";
Key = "Path";
Registry Type = "REG_SZ"

Above parameters basically tells, what is the Andriod SDK Tools 'Path' directory ? That is what i want to figure it out.

Below piece of code, which will help you to get the Andriod sdk tools path directory.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WindowsRegistryReader {

public static void main(String[] args) {

String location = "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Android SDK Tools";
String key = "Path";
String regType = "REG_SZ";

try {
String value = read(location, key, regType);
System.out.println("==========Output=================");
System.out.println("location: " + location);
System.out.println("Type: " + regType);
System.out.println("key: " + key + "  value: " + value);
System.out.println("=================================");

} catch (IOException e) {
e.printStackTrace();
}
}

public static String read(String location, String name, String regType) throws IOException {

Process p = Runtime.getRuntime().exec("reg QUERY \"" + location + "\" /v \"" + name + "\"");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String out = "";
while ((out = in.readLine()) != null) {
if (out.matches("(.*)\\s+REG_(.*)")) {
break;
}
}
in.close();
if (out != null) {
int indexOf = out.indexOf(regType);
if (indexOf != -1) {
String value = out.substring(indexOf + regType.length()).trim();
return value;
}
}
return null;
}
}


Output:
==========Output=================
location: HKEY_LOCAL_MACHINE\Software\Wow6432Node\Android SDK Tools
Type: REG_SZ
key: Path  value: C:\Program Files (x86)\Android\android-sdk

=================================

Various Windows registry type values can be found @ http://msdn.microsoft.com/en-us/library/windows/desktop/ms724884(v=vs.85).aspx

No comments:

Post a Comment