List all environment variables in Java program

In this article we will understand how to fetch all environment variables in Java. It is often required to fetch environment variables and based on value, perform some specific operations.

Implementation

import java.util.Map;
import java.util.Set;

/**
 * @author Amit Gupta
 *
 */

public class SystemProperties {

	public static void main(String[] args) throws Exception {

		Map<String, String> envMap = System.getenv();

		Set<String> keySet = envMap.keySet();

		for (String key : keySet) {
			String value = envMap.get(key);
			System.out.println("[" + key + "]  ---- " + "[" + value + "]");
		}

	}

}

Output

[PROCESSOR_LEVEL]  ---- [6]
[M2]  ---- [C:\Java Configurations\apache-maven-3.3.9\bin]
[SESSIONNAME]  ---- [Console]
[ALLUSERSPROFILE]  ---- [C:\ProgramData]
[PROCESSOR_ARCHITECTURE]  ---- [AMD64]
[SystemDrive]  ---- [C:]
[ProgramFiles(x86)]  ---- [C:\Program Files (x86)]
[ProgramData]  ---- [C:\ProgramData]
[ProgramW6432]  ---- [C:\Program Files]
[PROCESSOR_IDENTIFIER]  ---- [Intel64 Family 6 Model 60 Stepping 3, GenuineIntel]
[M2_HOME]  ---- [C:\Java Configurations\apache-maven-3.3.9]
[ProgramFiles]  ---- [C:\Program Files]
[PUBLIC]  ---- [C:\Users\Public]
[windir]  ---- [C:\Windows]
[MAVEN_OPTS]  ---- [-Xms256m -Xmx512m]
[OS]  ---- [Windows_NT]
[windows_tracing_flags]  ---- [3]
[PROCESSOR_REVISION]  ---- [3c03]
[CommonProgramW6432]  ---- [C:\Program Files\Common Files]
[ComSpec]  ---- [C:\Windows\system32\cmd.exe]
[SystemRoot]  ---- [C:\Windows]
[HOMEDRIVE]  ---- [C:]
[CommonProgramFiles(x86)]  ---- [C:\Program Files (x86)\Common Files]
[NUMBER_OF_PROCESSORS]  ---- [4]

Similarly if you want to fetch any specific environment variable you can get it from the Map using it as a key as shown below -

import java.util.Map;

/**
 * @author Amit Gupta
 *
 */

public class SystemProperties {

	public static void main(String[] args) throws Exception {

		Map<String, String> envMap = System.getenv();

		System.out.println("[NUMBER_OF_PROCESSORS]  --------- " + envMap.get("NUMBER_OF_PROCESSORS"));

	}

}

Output

[NUMBER_OF_PROCESSORS]  --------- 4

In this article, we learnt how to fetch environment variables in Java.

Article tagged as
Author
Author: Amit Gupta
Published On: 28/05/2016
Last revised On: 28/05/2016
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media