Passing environment variables to a JVM, in a platform-independent manner
Asked Answered
A

3

29

I'm developing a J2EE application that runs in JBoss on a Windows Vista machine, but the application will end up on a Linux machine. Is there a way to pass in the value of an environment variable in a platform independent way?

I think (but I'm not sure) the platform-sensitive way would be:

-Denv_var=%MY_ENV_VAR% (Windows)
-Denv_var=$MY_ENV_VAR (Linux)

and from there I would access the value (in Java) using

System.getProperty("MY_ENV_VAR");

— is that correct?

The Javadoc for System.getenv(String name) seem to imply that method is platform-dependent, but I'm not clear on that. Could I just skip passing the variable into the JVM completely, and use getenv() after using setting the value for an environment variable using the OS?

Altogether answered 22/9, 2009 at 19:20 Comment(1)
Is your example wrong? Shouldn't it be -DMY_ENV_VAR if you are going to use System.getProperty("MY_ENV_VAR");Serb
L
33

System.getenv() is platform-independent by itself. Using your above example, you can most certainly write

String value = System.getenv("MY_ENV_VAR")

and it will work on both Linux and Windows. No reason to wrap this into java system property. That said, the "platform-dependent" part of getenv() lies in the fact that different operating systems use different environment variables, like PATH on windows vs path on Linux. But as long as you're using your own variables and name them consistently (always uppercase, for example), you'll be fine.

Lapierre answered 22/9, 2009 at 19:31 Comment(3)
So, if I use System.getEnv() I don't have to pass anything into the JVM?Altogether
This is just for reading environment variables. Yes you still have to set them.Thigpen
You have to set them in your target OS (e.g. set MY_ENV_VAR=WHATEVER). You don't have to pass them into JVM as command-line arguments (no need for -DMY_ENV_VAR=$MY_ENV_VAR)Lapierre
L
1

How I interpret the java tutorial on this is that getenv works in a platform independent way, but that you have to keep in mind that variables are not consistently named across platforms. Since you seem to set the var yourself, this does not apply to you.

Laspisa answered 22/9, 2009 at 19:33 Comment(0)
A
1

Yes - getEnv() will just return the name of the environment variable, and you can set it in whatever way is appropriate to the platform you're running on (typically via a launch batch file on Win32). It's good practice to fall back on sensible defaults based on the platform (by inspecting System.getProperty("os.name")), if it's possible you want to avoid having your users bother with needing to mess with environmental variables to run your software.

Afloat answered 22/9, 2009 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.