分享

JAVA读取环境变量 - ritaleo - JavaEye技术网站

 julyfire 2010-11-26
Java代码
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3. import java.util.Properties;  
  4.   
  5. class Test  
  6. {  
  7.  // 返回当前系统变量的函数,结果放在一个Properties里边,这里只针对win2k以上的,其它系统可以自己改进  
  8.  public Properties getEnv() throws Exception  
  9.  {  
  10.   Properties prop = new Properties();  
  11.   String OS = System.getProperty("os.name").toLowerCase();  
  12.   System.out.println("操作系统:" + OS);  
  13.   Process p = null;  
  14.   if (OS.indexOf("windows") > -1)  
  15.   {  
  16.    p = Runtime.getRuntime().exec("cmd /c set");  
  17.   }  
  18.    if(OS.indexOf("linux") > -1)  
  19.          {  
  20.             p = Runtime.getRuntime().exec("sh -c set");  
  21.          }  
  22.   BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));  
  23.   String line;  
  24.   while ((line = br.readLine()) != null)  
  25.   {  
  26.    int i = line.indexOf("=");  
  27.    if (i > -1)  
  28.    {  
  29.     String key = line.substring(0, i);  
  30.     String value = line.substring(i + 1);  
  31.     prop.setProperty(key, value);  
  32.    }  
  33.   }  
  34.   return prop;  
  35.  }  
  36.   
  37.  // 具体用法  
  38.  public static void main(String[] args)  
  39.  {  
  40.   try  
  41.   {  
  42.    Test sp = new Test();  
  43.    Properties p = sp.getEnv();  
  44.    System.out.println(p.getProperty("PATH")); // 注意大小写,比如读取PATH。Linux下为PATH;Windows为Path  
  45.   }  
  46.   catch (Exception e)  
  47.   {  
  48.    System.out.println(e);  
  49.   }  
  50.  }  
  51. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多