Topquan's Blog

分享价值----成就你我----我的博客----你的家

用java访问windows注册表

 自从jdk1.4,java可以通过java.util.prefs包访问注册表,但访问的范围非常小,只能是HKLM和HKCU的javasoft子项下的prefs项(不知道我的理解是否正确?)。
 
  要想通过java访问整个注册表,可以通过开源代码给予实现。现在这样的开源很多,基本原理都差不多通过JNI实现的,如http://trustice.com/java/jnireg/就是其中一个。

  准备工作:
  到trustice网站下载其API和dll文件。我下的是registry-3.1.3.zip(URL:ftp://ftp.gjt.org/pub/users/time/java/registry-3.1.3.zip)。解压后,在其下的bin文件夹下就有我们想要registry.jar和dll文件。
 
  轻装上阵
  第一步,在eclipse新建一个java项目-registry,并把jar文件引进来;把dll文件放到classpath下,如c:\winnt(windows)。
  第二步,建立一个简单的测试单元
package com.mascot.myregistry;

import com.ice.jni.registry.*;

public class test {
    public static void main(String[] str) {
        try {
              RegistryKey child = Registry.HKEY_LOCAL_MACHINE
                      .openSubKey("SOFTWARE\\Microsoft");

              RegistryKey create = child.createSubKey("Mascot", "");
              create.setValue(new RegStringValue(create,"hello1","hello000"));
              create.setValue(new RegStringValue(create,"hello2","hello222"));
              System.out.println(childs.getFullName());
        } catch (Exception e) {
              e.printStackTrace();
        }
    }

}
其中的child是本机注册表的HKLM\SOFTWARE\Microsoft,并通过createSubKey创建Mascot子项,通过setValue为Mascot创建两个REG_SZ子项hello1、hello2,数据分别是hello000,hello222
 
  第三步,运行程序,就可以看到注册表多了一个mascot项等等。

  当然,该开源的功能不仅如此,我们还可以实现对注册表进行CRUD,还可以通过RegistryKey的connectRegistry连接远程注册表。

posted on 2006-10-14 16:25 topquan 阅读(2050) 评论(0)  编辑  收藏 所属分类: JAVA Base&App


只有注册用户登录后才能发表评论。


网站导航: