您的位置:首页 > 编程语言 > Java开发

用JAVA读取系统的环境变量

2010-02-06 15:12 323 查看
import java.io.BufferedReader;     

import java.io.InputStreamReader;     

import java.util.Properties;     

    

class Test     

{     

 // 返回当前系统变量的函数,结果放在一个Properties里边,这里只针对win2k以上的,其它系统可以自己改进     

 public Properties getEnv() throws Exception     

 {     

  Properties prop = new Properties();     

  String OS = System.getProperty("os.name").toLowerCase();     

  System.out.println("操作系统:" + OS);     

  Process p = null;     

  if (OS.indexOf("windows") > -1)     

  {     

   p = Runtime.getRuntime().exec("cmd /c set");     

  }     

   if(OS.indexOf("linux") > -1)     

         {     

            p = Runtime.getRuntime().exec("sh -c set");     

         }     

  BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));     

  String line;     

  while ((line = br.readLine()) != null)     

  {     

   int i = line.indexOf("=");     

   if (i > -1)     

   {     

    String key = line.substring(0, i);     

    String value = line.substring(i + 1);     

    prop.setProperty(key, value);     

   }     

  }     

  return prop;     

 }     

    

 // 具体用法     

 public static void main(String[] args)     

 {     

  try    

  {     

   Test sp = new Test();     

   Properties p = sp.getEnv();     

   System.out.println(p.getProperty("Path")); // 注意大小写,比如读取PATH。Linux下为PATH;Windows为Path     

  }     

  catch (Exception e)     

  {     

   System.out.println(e);     

  }     

 }     

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息