Get Environment Variables in Java

In Java 1.5, Sun had decided to "undeprecate" the getEnv() method that provides the functionality to get the value of an environment variable. In addition, Sun has added a new method that allows you to discover all of the environment variables that are defined. This Java tutorial walks you through using both the old and new methods.

To get the value of a single environment variable, you simply need to call the getEnv("environment variable") method providing the environment variable name that you want to evaluate. The following is a simple example:

String variable = System.getenv("WINDIR");
System.out.println(variable);

In Java 1.5, a new method was introduced to allow you to discover all of the environment variables defined in the system. The following example uses the new method to print all of the environment variables and their values:
Map<String, String> variables = System.getenv();

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


7 comments:

Anonymous said...

just wondering why not use the foreach loop, rather than the old iterator-for way...

eh... just being picky.

Code Beach said...

Good point! The example has been updated to use the foreach loop.

Anonymous said...

ProcessBuilder allows you to set environemt variables when starting a new process, but how do you set them to affect the current Java process?

jagadevi said...

Is it possible to set environment variable in Java ?

Dejan said...

try something like this

import java.io.File;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

public class test {
public test() {
/* try
{
Runtime runtime = Runtime.getRuntime();

Process proc = runtime.exec("EXCEL.EXE");
} catch (Exception e)
{
e.printStackTrace();
}*/
String variable = System.getenv("PATH");
System.out.println(variable);
String[] folders = variable.split(";");
// String folder;
for (String folder : folders)
{
System.out.println("dir: "+folder);
//System.out.println("JE2 " + folder + "\\AcroRd32.exe");
if
(new File(folder + "AcroRd32.exe").exists() )
{
System.out.println("JE "+folder + "AcroRd32.exe");
}
else if (new File(folder + "\\AcroRd32.exe").exists())
{
System.out.println("JE2 "+folder + "\\AcroRd32.exe");
try
{
Runtime runtime = Runtime.getRuntime();

Process proc = runtime.exec(folder + "\\AcroRd32.exe");
} catch (Exception e)
{
e.printStackTrace();
}
}

}

}
public static void main(String[] args) {
test test = new test();
}
}

Ghaylen said...

Thank you very much
Very usefull post ;)

Anonymous said...

Useful Post. Thks a lot :)

Post a Comment