Saturday 28 May 2011

Environment variables in java

Unlike C or C++, there is no getEnv() method in Java.

Part of the reason is that Java could conceivably be run on a platform that does not support the concept of environment variables. The expected way to pass environment-variable-like values to a Java application is with the -Dname=value syntax seen a few times in earlier chapters. Using the -D syntax on the java command line effectively adds the specified name and value to the list of system properties. Therefore, if you need to send a system environment variable named SomeEnvVar to your Java code, you can include it on the command line like this:

java -Dsome.env.variable=$SomeEnvVar YourClass (Unix/Linux)

or

java -Dsome.env.variable=%SomeEnvVar% YourClass (Windows) 


Then you access the new system property as follows:

String some_value = System.getProperty ("some.env.variable"); 

Obviously, you can name the system property anything you want.



No comments:

Post a Comment