Java中擷取作業系統的環境變數
來源:互聯網
上載者:User
注意,這次是擷取作業系統的環境變數,而不是擷取JVM相關的一些變數(參見我之前的一篇Blog:在Java中擷取環境變數)。
也許是為了營造JVM就是作業系統平台的氣氛,抑或是為了強調Java的平台無關性,不知幾時起Java已經把System.getenv(String)函數廢棄了。所以一般來說Java只能擷取它自己定義的一些變數,而無法與作業系統的環境變數互動,只能在運行靠java的“-D”參數來設定要傳遞給它的一些變數。
所以唯一的辦法只能先判斷作業系統,然後用作業系統的命令來調出環境變數列表,設法獲得該輸出資料行表。下面轉載來自http://www.rgagnon.com/javadetails/java-0150.html的一個範例: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();
}
}
}