Java通过CMD方式读取注册表任意键值对代码实践

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java通过CMD方式读取注册表任意键值对代码实践

  2021-04-03 我要评论

需要读取如图所示注册表【HKEY_LOCAL_MACHINE\SOFTWARE\EasyDrv7】节点下的【DateTime】的值

直接上代码:

package com.beibei.common.util.cmd;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 注册表操作工具类
* @author 北北
* @date 2019年6月19日下午8:21:02
*/
public class RegistryUtil {
private static Logger logger = LoggerFactory.getLogger(RegistryUtil.class);
/**
* <pre>
* 读取注册表指定节点所有的键值对
* </pre>
* @author 北北
* @date 2019年6月19日下午8:43:56
* @param nodePath
* @return
*/
public static Map<String, String> readNode(String nodePath) {
Map<String, String> regMap = new HashMap<>();
try {
Process process = Runtime.getRuntime().exec("reg query " + nodePath);
process.getOutputStream().close();
InputStreamReader isr = new InputStreamReader(process.getInputStream());
String line = null;
BufferedReader ir = new BufferedReader(isr);
while ((line = ir.readLine()) != null) {
String[] arr = line.split(" ");
if(arr.length != 4){
continue;
}
regMap.put(arr[1], arr[3]);
}
process.destroy();
} catch (IOException e) {
logger.error("读取注册表失败, nodePath: " + nodePath, e);
}
return regMap;
}
/**
* <pre>
* 读取注册表指定节点指定key的值
* </pre>
* @author 北北
* @date 2019年6月19日下午8:43:24
* @param nodePath
* @param key
* @return
*/
public static String readValue(String nodePath, String key) {
Map<String, String> regMap = readNode(nodePath);
return regMap.get(key);
}
public static void main(String[] args) {
String paramValue = RegistryUtil.readValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\EasyDrv7", "DateTime");
System.out.println(paramValue);
}
}

其原理是通过CMD命令【reg query HKEY_LOCAL_MACHINE\SOFTWARE\EasyDrv7】 读取节点全部键值对,再通过解析得到我们所需要的【DateTime】的值。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们