美文网首页
Java通过CMD方式读取注册表任意键值对

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

作者: 李北北 | 来源:发表于2019-06-20 10:05 被阅读0次

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


    image.png

    直接上代码:

    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】的值。

    相关文章

      网友评论

          本文标题:Java通过CMD方式读取注册表任意键值对

          本文链接:https://www.haomeiwen.com/subject/clzrqctx.html