Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 667
Matt Ball Avatar asked Sep 22 '09 19:09

Matt Ball


People also ask

What environment variables should be set for Java PATH?

For Java applications, PATH must include the following directories: JDK's " bin " (binary) directory (e.g., " c:\Program Files\java\jdk1. x.x\bin "), which contains JDK programs such as Java Compiler " javac.exe " and Java Runtime " java.exe ".

Do we need to set environment variables for JDK?

Java does not need any environment variables to be set. However, setting some environment variables makes some things easier. PATH If the jre/bin folder is on the path, you don't have to qualify to run the java command. If the jdk/bin folder is on the path, you don't have to qualify to run the java and javac commands.

What is system Getenv in Java?

getenv(String name) method gets the value of the specified environment variable. An environment variable is a system-dependent external named value. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).


2 Answers

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.

like image 150
ChssPly76 Avatar answered Sep 19 '22 15:09

ChssPly76


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.

like image 44
Alexander Torstling Avatar answered Sep 20 '22 15:09

Alexander Torstling