Read/Write to Windows Registry Using Java

How to read integer value from Windows registry using Java?

I have found the solution:

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

public class ReadRegistry
{
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+");

String s1[];
try{
s1=reader.getResult().split("REG_SZ|REG_DWORD");
}
catch(Exception e)
{
return " ";
}
//MK System.out.println(s1[1].trim());

return s1[1].trim();
} 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)
//System.out.println(c);
sw.write(c);
} catch (IOException e) {
}
}

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

You have to use it like this:

Registry2.readRegistry("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\LanmanWorkstation\\Parameters", "EnableSecuritySignature");

The class was taken from here.

How can I read the registry values using java?

This shows how to read the registry, but could be extended to write operations: How to read the Windows Registry

import java.io.*;

public class RegQuery {

private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";

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

public static String getCurrentUserPersonalFolderPath() {
try {
Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD);
StreamReader reader = new StreamReader(process.getInputStream());

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

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

if (p == -1)
return null;

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

public static String getCPUSpeed() {
try {
Process process = Runtime.getRuntime().exec(CPU_SPEED_CMD);
StreamReader reader = new StreamReader(process.getInputStream());

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

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

if (p == -1)
return null;

// CPU speed in Mhz (minus 1) in HEX notation, convert it to DEC
String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
return Integer.toString
((Integer.parseInt(temp.substring("0x".length()), 16) + 1));
}
catch (Exception e) {
return null;
}
}

public static String getCPUName() {
try {
Process process = Runtime.getRuntime().exec(CPU_NAME_CMD);
StreamReader reader = new StreamReader(process.getInputStream());

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

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

if (p == -1)
return null;

return result.substring(p + REGSTR_TOKEN.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[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}

How to get registry values with java?

You can use java.util.prefs.Preferences

Preferences p = Preferences.userRoot();
for user preferences and
Preferences p = Preferences.systemRoot();
for system preferences

and then accessing each path

if(p.nodeExists("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall") {
p = p.node("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall");

}

how to read registry in java

You can use java.util.prefs to read and write to the registry. See this question for some examples.

How to write windows registry using Java?

Download jna libraries from here. Add jna-4.1.0.jar and jna-platform-4.1.0.jar files to your application classpath. And use Advapi32Util utility class to read, write or delete the registery keys. I test some of the solutions but most of them dont work. but jna version works pretty well and has lots of features.

Here is my test code to update Chromium lastrun value.

import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;

public class Main {

public static void main(String[] args) throws Exception {
Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, "Software\\Chromium", "lastrun", "13031598735788802");
}
}

Finding a specific registry key using java in windows

I will use this class for your answer. Because it is written in pure java code.

  1. Have a WinRegistry class from here.
  2. Get a list of all keys in parent key.
  3. filter list to get the most appropriate key (Or exact key).
  4. Then you can check the value you want in this key.

Here is the code to help you :

List<String> ls = WinRegistry.readStringSubKeys(WinRegistry.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
String key = ls.stream().filter(st -> st.matches("Maxima.*")).findAny().get();

Now this key value will be Maxima-5.17.1_is1 (if present otherwise java.util.NoSuchElementException will be thrown). And you can use it to get any Value.

How to read windows registry data on remote machine using java

WinAPI has a function named RegConnectRegistry which may be what you're looking for:

Establishes a connection to a predefined registry key on another computer

LONG WINAPI RegConnectRegistry(
_In_opt_ LPCTSTR lpMachineName,
_In_ HKEY hKey,
_Out_ PHKEY phkResult
);

In Java, the function may look like the following, granted that you've added the jna-platform library as a dependency which provides ready-made API types and functions:

import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;
import com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE;
import com.sun.jna.win32.W32APIOptions;

interface MyAdvapi32 extends StdCallLibrary {
MyAdvapi32 INSTANCE = (MyAdvapi32) Native.loadLibrary(
"advapi32",
MyAdvapi32.class,
W32APIOptions.DEFAULT_OPTIONS
);

int RegConnectRegistry(String machineName, HKEY hKey, HKEYByReference result);
int RegCloseKey(HKEY key);
}

You might notice the W32APIOptions.DEFAULT_OPTIONS used in the library load. The Windows API provides two different implementations for functions which use strings: one for Unicode strings and one for ANSI strings. While the function is named RegConnectRegistry, the implementations which JNA finds in the DLL are named RegConnectRegistryW (Unicode) and RegConnectRegistryA (ANSI). However, these probably are not your concern since you're not writing native code.

Passing the default options in lets JNA use the correct function names, avoiding a confusing-at-best UnsatisfiedLinkError.

Usage might look like this:

HKEYByReference result = new HKEYByReference();
int returnCode = MyAdvapi32.INSTANCE.RegConnectRegistry(
"\\\\server-name",
HKEY_LOCAL_MACHINE,
result
);

if (returnCode != 0) {
throw new Win32Exception(returnCode);
}

HKEY key = result.getValue();

// ... use the key, then once done with it ...

MyAdvapi32.INSTANCE.RegCloseKey(key);

By the way, jna-platform library does provide mappings for the Advapi32 library, but RegConnectRegistry seems to be missing. Ideally, you'd probably create a pull request and add it in, but YMMV as to how quickly they roll out a new release with the addition.

EDIT: I've created a pull request to JNA to get this function added in.



Related Topics



Leave a reply



Submit