天天看點

在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();

}

*