天天看点

在Java中获取环境变量

在jdk1.5中可以通过System.getenv()获取系统环境变量System.out.println( "CLASSPATH = " + System.getenv("CLASSPATH"));,但是在jdk1.4.2中该方法不能用,请问还有什么办法获取系统环境变量,向linux中的getenv一样?

注意,这次是获取操作系统的环境变量,而不是获取JVM相关的一些变量(参见下面JVM段).

  也许是为了营造JVM就是操作系统平台的气氛,抑或是为了强调Java的平台无关性,不知几时起Java已经把System.getenv(String)函数废弃了。所以一般来说Java只能获取它自己定义的一些变量,而无法与操作系统的环境变量交互,只能在运行靠java的“-D”参数来设置要传递给它的一些变量。

  所以唯一的办法只能先判断操作系统,然后用操作系统的命令来调出环境变量列表,设法获得该输出列表。下面转载来自http://www.rgagnon.com/javadetails/java-0150.html的一个范例:

Code:

package test;

import java.io.*;

import java.util.*;

public class ReadEnv {

public static Properties getEnvVars() throws Throwable {

Process p = null;

Properties envVars = new Properties();

Runtime r = Runtime.getRuntime();

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

// System.out.println(OS);

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

p = r.exec("command.com /c set");

} else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 20") > -1)

|| (OS.indexOf("windows xp") > -1)) {

// thanks to JuanFran for the xp fix!

p = r.exec("cmd.exe /c set");

} else {

// our last hope, we assume Unix (thanks to H. Ware for the fix)

p = r.exec("env");

}

BufferedReader br = new BufferedReader(new InputStreamReader(p

.getInputStream()));

String line;

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

int idx = line.indexOf('=');

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

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

envVars.setProperty(key, value);

// System.out.println( key + " = " + value );

return envVars;

}

public static void main(String args[]) {

try {

Properties p = ReadEnv.getEnvVars();

System.out.println("the current value of TEMP is : "

+ p.getProperty("TEMP"));

} catch (Throwable e) {

e.printStackTrace();

}

*