ritaleo 发表于 2013-1-15 03:08:46

JAVA读取环境变量

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);} }} 
页: [1]
查看完整版本: JAVA读取环境变量