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.

3
  • you want that variable read by non jvm process? Commented Oct 25, 2013 at 22:46
  • Here's how: stackoverflow.com/questions/318239/… Commented Oct 25, 2013 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. Commented Oct 25, 2013 at 22:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.