java 不能直接修改windows系統的環境變量,需要借助JNI轉為C++的接口,以調用windows系統的注冊表
如其說修改環境變量,不如說修改注冊表更準確些,因為是通過修改注冊表來實現修改環境變量的;“環境變量”的鍵值所在位
置:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment
Windows Registry API Native Interface下載地址
http://www.trustice.com/java/jnireg/index.shtml 下
registry-3.1.3.zip(包含源代碼)。解開 registry-3.1.3.zip,在 bin 目錄中可以看到兩個文件
ICE_JNIRegistry.dll 和registry.jar,動態庫就是本地代碼實現。
1 package frame;
2
3 import java.io.BufferedReader;
4 import java.io.InputStreamReader;
5
6 import com.ice.jni.registry.RegStringValue;
7 import com.ice.jni.registry.Registry;
8 import com.ice.jni.registry.RegistryKey;
9
10 public class TestRegistry {
11
12 /**
13 * @param args
14 */
15 public static void main(String[] args) {
16 // TODO Auto-generated method stub
17 try {
18 //RegistryKey openPath1
19 // = Registry.HKEY_LOCAL_MACHINE.openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
20 //String path_Old = openPath1.getStringValue("PAODING_DIC_HOME"); //獲取原Path鍵值
21 //System.out.println(path_Old);
22 //System.out.println(System.getProperty("user.dir"));
23
24 RegistryKey openPath2
25 = Registry.HKEY_LOCAL_MACHINE.openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager");
26 RegistryKey subKey = openPath2.createSubKey("Environment", "");
27 subKey.setValue(new RegStringValue(subKey, "PAODING_DIC_HOME", "D:\\PaodingEnv\\Dic")); //修改Path鍵值
28 subKey.closeKey();
29 /*RegistryKey openPath2
30 = Registry.HKEY_LOCAL_MACHINE.openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager");
31
32 RegistryKey subKey = openPath2.createSubKey("Environment", "");
33 //定義Path所在目錄的句柄(相當于在Session Manager路徑下面,新建Environment文件夾,如果存在不改變已有的值。)
34 // String path_New = path_Old + ";" + "D:\\myTinoProject\\bingy";
35 String path_New = path_Old + "bin;";
36 subKey.setValue(new RegStringValue(subKey, "Path", path_New)); //修改Path鍵值
37 subKey.closeKey();
38 //查看進程的方法
39 String[] cmd = { "D:\\dfqd\\workspace\\tasklist" };
40 Process proc = Runtime.getRuntime().exec(cmd);
41 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
42 String string_Temp = in.readLine();
43 while (string_Temp != null) {
44 System.out.println(string_Temp);
45 string_Temp = in.readLine();
46 }
47 //刪除explorer.exe進程
48 Process proc2 = Runtime.getRuntime().exec("D:\\dfqd\\workspace\\taskkill /F /IM explorer.exe");
49 Thread.sleep(500);
50 //重啟explorer.exe進程
51 Process proc3 = Runtime.getRuntime().exec("explorer.exe");
52 System.out.println("=====SUCCESS=====");*/
53 }
54 catch (Exception e) {
55 e.printStackTrace();
56 }
57 }
58 }
59