Java执行wmic命令获取系统环境变量

来源:互联网 发布:电子教室软件 编辑:程序博客网 时间:2024/05/22 16:52

1.首先编写文件setenv.bat设置系统环境变量:

echo %cd%set framework_home=%cd%echo %framework_home%wmic ENVIRONMENT create name="framework_home",username="<system>",VariableValue="%framework_home%"

Note:

此处假设framework_home为要添加的系统环境变量,且其值为当前路径。Windows系统有两种环境变量:用户变量和系统变量。上面设置的是系统变量。

2.编写Java程序读取上面设置的系统环境变量:

package test.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;class StreamDrainerThread implements Runnable{private InputStream ins;public static String environmentValue;public StreamDrainerThread(InputStream ins){this.ins = ins;}public void run(){try{BufferedReader reader = new BufferedReader(new InputStreamReader(ins));String line = null;while ((line = reader.readLine()) != null){if (!line.trim().equals("")){environmentValue = line;}}} catch (Exception e){e.printStackTrace();}}}public class WMICJava{public static void main(String[] args) throws IOException{String[] cmd = new String[]{ "cmd.exe", "/C", "wmic ENVIRONMENT where \"name=\'framework_home\'\" get VariableValue" };try{Process process = Runtime.getRuntime().exec(cmd);StreamDrainerThread streamDrainer = new StreamDrainerThread(process.getInputStream());new Thread(streamDrainer).start();process.getOutputStream().close();process.waitFor();System.out.println("Environment Parameter OATS_HOME is " + StreamDrainerThread.environmentValue);} catch (Exception e){e.printStackTrace();}}}

参考:

【1】java Runtime 执行 windows wmic 命令
http://hi.baidu.com/kelongxhu/blog/item/7ed96dfb028c9b354f4aeab1.html

原创粉丝点击