JAVA 获取系统环境变量

时间:2025-05-13 15:07:44

分享代码:

 package com.base.entity;

 import java.io.Serializable;
import java.util.Comparator; /**
* 系统环境变量
*
* @author test
* @create 2014-3-10下午04:35:47
* @version 1.0
*/
public class SystemProperty implements Serializable, Comparator { private static final long serialVersionUID = 1L; // 属性key
private String iKey; // 属性Value
private String iVal; public SystemProperty() {
// TODO Auto-generated constructor stub
} public SystemProperty(String iKey, String iVal) {
super();
this.iKey = iKey;
this.iVal = iVal;
} @Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub SystemProperty s1 = (SystemProperty) o1;
SystemProperty s2 = (SystemProperty) o2; return s1.getiKey().compareTo(s2.getiKey());
} public String getiKey() {
return iKey;
} public void setiKey(String iKey) {
this.iKey = iKey;
} public String getiVal() {
return iVal;
} public void setiVal(String iVal) {
this.iVal = iVal;
}
}
 package com.util.common;

 import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import com.base.entity.SystemProperty; /**
* @author test
* @create 2014-3-10下午04:39:08
* @version 1.0
*/
public final class Read { /**
* 获取系统所有环境变量
*
* @return List<SystemProperty>
* @throws Exception
*/
public static List<SystemProperty> readSysPropertyAll() throws Exception {
return readSysProperty("BOCO_ALL");
} /**
* 获取系统指定环境变量
*
* @param key
* 环境变量Key
* @return List<SystemProperty>
* @throws Exception
*/
public static List<SystemProperty> readSysProperty(String key)
throws Exception { List<SystemProperty> list = new ArrayList<SystemProperty>(); Map m = System.getenv();
String keys = "";
if (key.equals("BOCO_ALL")) {
for (Iterator<String> iter = m.keySet().iterator(); iter.hasNext();) {
keys = iter.next();
list.add(new SystemProperty(keys, m.get(keys).toString()));
Collections.sort(list, new SystemProperty());
}
} else {
if (m.containsKey(key)) {
list.add(new SystemProperty(key, m.get(key).toString()));
} else {
throw new Exception("系统中未包含指定Key:" + key);
}
}
return list;
}
}