Created
February 28, 2015 00:03
-
-
Save rmorenobello/71cf6bca8a47216192fe to your computer and use it in GitHub Desktop.
Set and Retrieve environment (OS) variables in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OS Environment Variables | |
// ======================= | |
// http://docs.oracle.com/javase/tutorial/essential/environment/env.html | |
/* | |
Windows provides the user name in an environment variable called USERNAME, | |
while UNIX implementations might provide the user name in USER, LOGNAME, or both. | |
To maximize portability, if the env var you need is available as java system property, always use getProperty(). | |
For example, if the operating system provides a user name, it will always be available in the system property user.name. | |
*/ | |
/* | |
Environment variables are set in the OS, eg in linux | |
export HOME=/Users/myusername | |
or on windows | |
SET WINDIR=C:\Windows | |
etc., and, unlike system properties, may not be set at runtime. | |
Java chose to expose OS environment variables as Properties with | |
System.getEnv() or System.getEnv(variable) | |
(just as Java exposes current directory and "other stuff" as Properties). | |
*/ | |
// Retrieving Env Variables | |
import java.util.Map; | |
public class EnvMap { | |
public static void main (String[] args) { | |
Map<String, String> env = System.getenv(); | |
for (String envName : env.keySet()) { | |
System.out.format("%s=%s%n", | |
envName, | |
env.get(envName)); | |
} | |
} | |
} | |
public class Env { | |
public static void main (String[] args) { | |
for (String env: args) { | |
String value = System.getenv(env); | |
if (value != null) { | |
System.out.format("%s=%s%n", | |
env, value); | |
} else { | |
System.out.format("%s is" | |
+ " not assigned.%n", env); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment