2009-06-26 28 views

回答

1

你绝对没有办法直接从java API访问环境变量。只有这样,才能实现与的Runtime.exec这样的代码:

Process p = null; 
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 2000") > -1) 
     || (OS.indexOf("windows xp") > -1)) { 
    // thanks to JuanFran for the xp fix! 
    p = r.exec("cmd.exe /c set"); 
} 

虽然你可以访问感谢System.getProperties的Java变量(); 但你只会得到一些ENV变量由JVM本身映射,以及额外的数据,你可以提供关于java命令行用“-Dkey =价值”

欲了解更多信息,请参阅http://www.rgagnon.com/javadetails/java-0150.html

+0

这是有帮助的..我只是使用echo%env_variable_name%直接获取值,而不必分析SET的输出。 – 2009-06-29 09:39:28

+1

我没有学习Java来将命令输入cmd =/ – 2012-05-11 01:03:30

1

将它们传递到JVM中-D系统属性,例如:

java -D<java var>=%<environment var>% 

这样你就不会被绑定到特定的操作系统。

4

有一个切换到JVM为此。从here

Start the JVM with the "-D" switch to pass properties to the application and read them with the System.getProperty() method.

SET myvar=Hello world 
SET myothervar=nothing 
java -Dmyvar="%myvar%" -Dmyothervar="%myothervar%" myClass 

then in myClass

String myvar = System.getProperty("myvar"); 
String myothervar = System.getProperty("myothervar"); 
7

您可以用getenv()获取环境变量:

String variable = System.getenv("WINDIR"); 
System.out.println(variable); 

相信GETENV()函数在某一时刻被弃用,但然后在java 1.5中“undeprecated”

ETA:

我现在看到的问题是专门针对java 1.4的,所以这对您不起作用(或者至少您可能会以弃用警告结束)。我会在这里留下答案,以防其他人绊倒这个问题并使用更高版本。

0
Map<String, String> env = System.getenv(); 
for (String envName : env.keySet()) { 
    System.out.format("%s=%s%n", envName, env.get(envName)); 
} 
0

阿帕奇百科全书Exec用“org.apache.commons.exec.environment.EnvironmentUtils”提供了一种方式来获得对环境变量JDK事先1.5:

(String) EnvironmentUtils.getProcEnvironment().get("SOME_ENV_VAR")