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

来源:互联网 发布:蓝牙模块调试软件 编辑:程序博客网 时间:2024/06/06 04:58

转:http://blog.csdn.net/weiyangcau/article/details/7617839

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

[html] view plaincopy
  1. echo %cd%  
  2. set framework_home=%cd%  
  3. echo %framework_home%  
  4. wmic ENVIRONMENT create name="framework_home",username="<system>",VariableValue="%framework_home%"  

Note:

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

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

[html] view plaincopy
  1. package test.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7.   
  8. class StreamDrainerThread implements Runnable  
  9. {  
  10.     private InputStream ins;  
  11.   
  12.     public static String environmentValue;  
  13.   
  14.     public StreamDrainerThread(InputStream ins)  
  15.     {  
  16.         this.ins = ins;  
  17.     }  
  18.   
  19.     public void run()  
  20.     {  
  21.         try  
  22.         {  
  23.             BufferedReader reader = new BufferedReader(new InputStreamReader(ins));  
  24.             String line = null;  
  25.             while ((line = reader.readLine()) != null)  
  26.             {  
  27.                 if (!line.trim().equals(""))  
  28.                 {  
  29.                     environmentValue = line;  
  30.                 }  
  31.             }  
  32.         } catch (Exception e)  
  33.         {  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  
  37.   
  38. }  
  39.   
  40. public class WMICJava  
  41. {  
  42.     public static void main(String[] args) throws IOException  
  43.     {  
  44.         String[] cmd = new String[]  
  45.         { "cmd.exe", "/C", "wmic ENVIRONMENT where \"name=\'framework_home\'\" get VariableValue" };  
  46.         try  
  47.         {  
  48.             Process process = Runtime.getRuntime().exec(cmd);  
  49.             StreamDrainerThread streamDrainer = new StreamDrainerThread(process.getInputStream());  
  50.             new Thread(streamDrainer).start();  
  51.             process.getOutputStream().close();  
  52.             process.waitFor();  
  53.             System.out.println("Environment Parameter OATS_HOME is " + StreamDrainerThread.environmentValue);  
  54.         } catch (Exception e)  
  55.         {  
  56.             e.printStackTrace();  
  57.         }  
  58.     }  
  59. }  


 

0 0
原创粉丝点击