Skip to content

Instantly share code, notes, and snippets.

@pcdavid
Created July 18, 2009 12:58
Show Gist options
  • Save pcdavid/149551 to your computer and use it in GitHub Desktop.
Save pcdavid/149551 to your computer and use it in GitHub Desktop.
GetEnv.java
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Simple example of how to access environment variables in pure Java on Linux in pre-1.5 Java.
* Since Java 1.5, System.getenv() can do this in a more portable way.
*/
public class GetEnv {
public static Map getEnvironment() {
Map env = new HashMap();
LineNumberReader reader = null;
try {
reader = new LineNumberReader(new FileReader("/proc/self/environ"));
String[] lines = reader.readLine().split("\000");
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
int n = line.indexOf('=');
env.put(line.substring(0, n), line.substring(n+1));
}
} catch (Exception e) {
return null;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ioe) {
/* ignore */
}
}
return env;
}
public static String getEnv(String varName) {
return (String) getEnvironment().get(varName);
}
public static void main(String[] args) {
Map env = GetEnv.getEnvironment();
for (Iterator iter = env.keySet().iterator(); iter.hasNext();) {
String var= (String) iter.next();
System.out.println(var + "=" + env.get(var));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment