0

Is there a way to have a Java program set an environment variable in Windows and/or Linux system?

I'm creating a Java application for a desktop system, which I hope will be used in Windows, Linux and Mac. But I'm unsure if I can make the installer set an environment variable for the application.

  • you want that variable read by non jvm process? – jmj Oct 25 '13 at 22:46
  • Here's how: http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java – Plasmarob Oct 25 '13 at 22:47
  • I was thinking of setting an [name]_home for the application i.e. so that other apps of the suite could always point to the right SQLite db. –  Oct 25 '13 at 22:49

2 Answers2

3

The environment is only ever passed into a child process, never out of a child process. So if what you want is to be able to write something like this:

java ProgramThatSetsAnEnvironmentVariable
java ProgramThatUsesTheEnvironmentVariable

then no, that's not possible.

But if what you want is to for a Java program to run a program, and you want it to pass in additional environment variables, then yes, that's possible, by using java.lang.ProcessBuilder's environment() method.

ruakh
  • 175,680
  • 26
  • 273
  • 307
0

This can be achieved via reflection.

Use the following code:

public static void setEnv(String key, String value) {
    try {
        Map<String, String> env = System.getenv();
        Class<?> cl = env.getClass();
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Map<String, String> writableEnv = (Map<String, String>) field.get(env);
        writableEnv.put(key, value);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to set environment variable", e);
    }
}