如何使用 exec 在 Java 中设置环境变量?
可能重复:
如何从 Java 设置环境变量?
我正在尝试设置一个环境变量,并将其读回以验证它是否已实际设置.
I'm trying to set an environment variable, and read it back to verify it was actually set.
我有以下内容:
import java.io.IOException;
public class EnvironmentVariable
{
public static void main(String[] args) throws IOException
{
Runtime.getRuntime().exec("cmd.exe set FOO=false");
String s = System.getenv("FOO");
System.out.println(s);
}
}
但是,FOO
似乎总是为空,这意味着它可能没有正确设置.
However, it appears that FOO
is always null, meaning its probably not set correctly.
我的 exec 命令是否正确?javadocs 声明它可以将字符串参数作为命令.
Do I have the exec command correct? The javadocs state it can take a string argument as the command.
有什么想法吗?
推荐答案
这行不通.当您启动一个新进程时,该进程会收到环境的副本.然后它对环境变量所做的任何更改都在该副本中进行,并且在任何时候都不会对调用者可见.
This won't work. When you start a new process, that process receives a copy of the environment. Any changes it then makes to environment variables are made within that copy, and at no point will become visible to the caller.
你真正想要达到什么目的?
What are you actually trying to achieve?
相关文章