Thursday, 21 April 2016

How to get environment variables in Java ?


Environment variables are stored in a small area of memory available to all running programs.

Environment variables in Windows
Set environment variables
Temporary and disappear on closing the command window
set var=C:\temp

Permanent setting
Right-click on My Computer and choose "Properties"
Click "Advanced" tab, Click the button "Environment Variables"
  • User variables : applies only to the current user
  • System variable : applies to the whole system

To display value of variable
echo %var%


Environment variables in Linux
To see a list of the environment variables that are already set
$ env

To set environment variable
$ var=$HOME/projects/src/test

To display value of variable
$ echo $var

Use export when creating variables to ensure they will be global in scope
$ export var=$HOME/projects/src/test


Get value of environment variables

For one variable
String variable = System.getenv("var");

For all variables
Map variables = System.getenv();
for (Map.Entry entry : variables.entrySet()) {
  String name = entry.getKey();     
  String value = entry.getValue();     
  System.out.println(name + "=" + value);  
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.