Ramesh-X
Ramesh-X

Reputation: 5055

How do I persistently define environment variables in Java on Windows?

Is there a way to change Windows environment variables using Java? I tried with the cmd function set:

Process exec = Runtime.getRuntime().exec(new String[] {
      "cmd", "/c", "set", "HTTP_PROXY=" + PROXY_URL
});

if (exec.waitFor() != 0) {
    throw new IllegalStateException("Output: "
        + getText(exec.getInputStream())
        + "Error: " + getText(exec.getErrorStream()
        + "\n"
        + "Exit value: " + exec.exitValue());
}

This code runs fine without any error but when I later check system variables nothing has changed.

I'm trying to update HTTP_PROXY so that other software run behind an HTTP proxy can use it.

Upvotes: 1

Views: 126

Answers (2)

phiology
phiology

Reputation: 29

It's impossible to do that (at least for forever). There are good reasons for that (isolation, java tools unknowingly changing your env). Look for a hack here :

edit:

a complex explanation was given by raffaele

Upvotes: 0

Raffaele
Raffaele

Reputation: 20875

Processes are launched in an enviroment made of name-value pairs. When a program writes to an env variable, it can optionally make that write visible to child processes, but when you check the value you are likely using another process (maybe run via cmd.exe) that has no access to the environment of your Java program.

I don't know if the purpose of your code is to define environment variables in a persistent manner, but if that's the case it can't be done in Java without specific OS tools and in a platform-independent way.

Environment variables default values must be stored by system tools in places where they are then read by the very same system tools from. On Linux there are files like .profile and .bashrc in the user home, while on Windows you have the registry. For example on my Windows 7 I have: my PATH default value stored in \HKEY_CURRENT_USER\Environment - so you must find a way to write to the system registry, for example the command reg

The REG ADD command allows the user to add new keys and values to the Registry. To display the full range of parameters that can be used, type the following into the command line: reg add /?

To add the key HKLM\Software\MyNewApp on remote computer PC2, type:

REG ADD \\PC2\HKLM\Software\MyNewApp

To add a registry entry to HKLM\Software\MyNewApp with a value named Data of type REG_BINARY and data of fe340ead, type:

REG ADD HKLM\Software\MyNewApp /v Data /t REG_BINARY /d fe340ead

You can either write a .bat script or call reg from your Java program. You may need administrator priviledges and to restart some programs (eventually the whole machine) for the update to take effect (for example restart explorer.exe)

Upvotes: 4

Related Questions