|
|
java 不能直接修改windows系统的环境变量,需要借助JNI转为C++的接口,以调用windows系统的注册表。(可以理解c++毕竟是微软推出的开发语言,OS源代码并未开放);目前,有开源项目实现了这个转换过程,使用版本:registry-3.1.3.zip;将压缩包bin目录中的jar包(registry.jar)导到工程中,然后在把相同目录下的dll(ICE_JNIRegistry.dll)放到jdk的bin目录下。
(ps:如其说修改环境变量,不如说修改注册表更准确些,因为是通过修改注册表来实现修改环境变量的;“环境变量”的键值所在位置:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment )
修改环境变量path 或 classpath ,代码如下:
package reg;import com.ice.jni.registry.RegStringValue;import com.ice.jni.registry.Registry;import com.ice.jni.registry.RegistryKey;public class RegistryTest { public static void main(String[] str) { try { RegistryKey openPath1 = Registry.HKEY_LOCAL_MACHINE .openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String path_Old = openPath1.getStringValue("Path"); //获取原Path键值 RegistryKey openPath2 = Registry.HKEY_LOCAL_MACHINE .openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager"); RegistryKey subKey = openPath2.createSubKey("Environment", ""); //定义Path所在目录的句柄(相当于在Session Manager路径下面,新建Environment文件夹,如果存在不改变已有的值。) String path_New = path_Old + ";" + "D:\\myTinoProject\\bin"; subKey.setValue(new RegStringValue(subKey, "Path", path_New)); //修改Path键值 subKey.closeKey(); } catch (Exception e) { e.printStackTrace(); } }}
注:如有下面的错误提示,句柄(subKey)未定义正确。
com.ice.jni.registry.RegistryException: Registry API Error 5, 'access denied' - 'RegSetValueEx()'
操作中会遇到一些问题
1、出现Registry API Error 5, 'access denied' - 'RegSetValueEx()' 错误,因为需要调用createSubKey("Environment", "");返回的subKey才可以setValue(); 不用担心 ,原来的不会消失
2、设置DWORD类型 range.setValue(new RegDWordValue(range, "1406", RegistryValue.REG_DWORD, 0));
3、dll文件位置的摆放,可以放到工程中,修改源码即可,修改源码如下,即loadlibary改成load方法(增强可移植性)
try {File file = File.createTempFile("ICE_JNIRegistry", ".dll");FileOutputStream fout = new FileOutputStream(file);InputStream in = Registry.class.getResourceAsStream("/ICE_JNIRegistry.dll");byte[] b = new byte[1024];int len = 0; while((len = in.read(b)) != -1){fout.write(b, 0, len);}fout.flush();in.close();fout.close();System.load(file.getAbsolutePath());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} |
|