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); } } }
java获取环境变量_用JAVA读取系统的环境变量
最新推荐文章于 2024-07-23 11:38:02 发布