通过java获取系统环境变量

代码如下:

 1        public   static  Map getEnv() {
 2           Map map  =   new  HashMap();
 3           String OS  =  System.getProperty( " os.name " ).toLowerCase();
 4           
 5           Process p  =   null ;
 6           
 7         /**
 8           * 以windows为例.
 9           */
10            if (OS.indexOf( " windows " >   - 1 ) {
11                try  {
12                   p  =  Runtime.getRuntime().exec( " cmd /c set " );
13                   BufferedReader br  =   new  BufferedReader( new  InputStreamReader(p.getInputStream()));
14                   
15                   String line;
16                   
17                    while ((line  =  br.readLine())  !=   null ) {
18                       String[] str  =  line.split( " = " );
19                       map.put(str[ 0 ], str[ 1 ]);
20                   }
21               }  catch (IOException ioe) {
22                   ioe.printStackTrace();
23               }
24           }
25            return  map;
26       }


上述代码将windows系统中的环境变量转换为java的Map,只要通过map.get(key)就能得到环境变量值,比如map.get("JAVA_HOME"),得到JAVA_HOME的值,即JAVA_HOME的系统路径。

值得注意的是在java中使用windows操作系统命令时要在命令前加 cmd /c ,否则java会报错(),错误列表如下:

 1   java.io.IOException: CreateProcess: ${执行的操作命令表达式或者.bat文件} error = 2
 2   at java.lang.Win32Process.create(Native Method)
 3   at java.lang.Win32Process. < init > (Win32Process.java: 63 )
 4   at java.lang.Runtime.execInternal(Native Method)
 5   at java.lang.Runtime.exec(Runtime.java: 566 )
 6   at java.lang.Runtime.exec(Runtime.java: 428 )
 7   at java.lang.Runtime.exec(Runtime.java: 364 )
 8   at java.lang.Runtime.exec(Runtime.java: 326 )
 9   at org.apache.jsp.ChangeDirBajaRCXX_jsp._jspService(ChangeDirBaja
10   p.java: 185 )


该错误的解释:

The error  2  comes from the CreateProcess() call, from MSDN (GetLastError():

2   -  The system cannot find the file specified.  -  ERROR_FILE_NOT_FOUND

So, it means the path you passed cannot be found. Maybe you did not configure your Runtime 
class  correctly.
put the batch file in the same directory as the 
class  file and use ( for  a test):

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值