用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 閱讀(2084) 評論(0) 編輯 收藏 所屬分類: JAVA Base&App