自從jdk1.4,java可以通過java.util.prefs包訪問注冊表,但訪問的范圍非常小,只能是HKLM和HKCU的javasoft子項(xiàng)下的prefs項(xiàng)(不知道我的理解是否正確?)。
要想通過java訪問整個(gè)注冊表,可以通過開源代碼給予實(shí)現(xiàn)。現(xiàn)在這樣的開源很多,基本原理都差不多通過JNI實(shí)現(xiàn)的,如
http://trustice.com/java/jnireg/就是其中一個(gè)。
準(zhǔn)備工作: 到trustice網(wǎng)站下載其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新建一個(gè)java項(xiàng)目-registry,并把jar文件引進(jìn)來;把dll文件放到classpath下,如c:\winnt(windows)。
第二步,建立一個(gè)簡單的測試單元
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是本機(jī)注冊表的HKLM\SOFTWARE\Microsoft,并通過createSubKey創(chuàng)建Mascot子項(xiàng),通過setValue為Mascot創(chuàng)建兩個(gè)REG_SZ子項(xiàng)hello1、hello2,數(shù)據(jù)分別是hello000,hello222
第三步,運(yùn)行程序,就可以看到注冊表多了一個(gè)mascot項(xiàng)等等。
當(dāng)然,該開源的功能不僅如此,我們還可以實(shí)現(xiàn)對注冊表進(jìn)行CRUD,還可以通過RegistryKey的connectRegistry連接遠(yuǎn)程注冊表。