【永恒的瞬间】
☜Give me hapy ☞
 Java中获取JVM环境变量是很简单的,下面两句就打印出了所有的JVM环境变量:
          Properties p = System.getProperties();
          p.list(System.out);
      如果想获得指定Key的值,则可以这样:System.getProperty(key);
      但如果想获取系统环境变量,就要想别的办法了。下面的代码可以实现:

package com.zhj.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
* 文件名:GetProperty.java
* 描述: 取得当前系统变量的程序。
*    java中的System.getProperty只是针对JVM来的,如果要取得系统环境变量,还要用到系统相关的函数。本程序先从JVM中取Key对应的Value,如果取不到再取系统环境变量
* 作者: 翟海军
*/
public class GetProperty {

/**
   * @param args
   * @throws IOException
   */
public static void main(String[] args) throws IOException {
   // TODO Auto-generated method stub
   String key=null;
   if (args.length>0) key=args[0];
   String s=getProperty(key);
   System.out.println(s);
  
}

public static String getProperty(String key) throws IOException{
   String value=null;
   Properties pp = null;
   if (key == null || key.length()<1) {
    pp = System.getProperties();
    System.out.println("未指定key,现列出所有JVM环境变量:");
    pp.list(System.out);
    value="未指定key,上面是所有JVM环境变量:";
    return value;
   } else {
    String s = null;
    value = System.getProperty(key);
    if (s == null) {
     String OS = System.getProperty("os.name").toLowerCase();
     Process p = null;
     if (OS.indexOf("windows") > -1) {
      p = Runtime.getRuntime().exec("cmd /c set"); // Windows系列
     } else if (OS.indexOf("linux") > -1 || OS.indexOf("aix") > -1
       || OS.indexOf("unix") > -1) {
      p = Runtime.getRuntime().exec("/bin/sh -c set"); // Unix系列
     }
     BufferedReader br = new BufferedReader(new InputStreamReader(p
       .getInputStream()));
     String line;
     while ((line = br.readLine()) != null) {
      int i = line.indexOf("=");
      if (i > -1) {
       if(key.equalsIgnoreCase(line.substring(0, i))){
        value = line.substring(i + 1);
        break;
       }      
      }
     }
    }
   
   }
   return value;
}

}

posted on 2007-04-13 08:42 ☜♥☞MengChuChen 阅读(2493) 评论(0)  编辑  收藏 所属分类: java_code

只有注册用户登录后才能发表评论。


网站导航: