import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; public class SystemProperties { public static String LINE_SEPARATOR = "line.separator"; public static String FILE_SEPARATOR = "file.separator"; public static String USER_LANGUAGE = "user.language"; public static String FILE_ENCODING = "file.encoding"; public static String OS_NAME = "os.name"; public static String USER_DIR = "user.dir"; public static String USER_COUNTRY = "user.country"; private static SystemProperties SystemPropertiesInstance = null; //零长度的byte数组对象创建起来将比任何对象都经济,查看编译后的字节码: //生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码 private static byte[] lockObject = new byte[0]; private HashMap<String,String> ptHashtable = null; private SystemProperties() { InitAllProperties(); } public static SystemProperties newInstance() { synchronized(lockObject) { if(null == SystemPropertiesInstance) { SystemPropertiesInstance = new SystemProperties(); } } return SystemPropertiesInstance; } public String getLineSeparator() { Object object = ptHashtable.get(LINE_SEPARATOR); if(null ==object) { return null; } return object.toString(); } public String getOSName() { Object object = ptHashtable.get(OS_NAME); if(null ==object) { return null; } return object.toString(); } public boolean isWindows() { if(getOSName().indexOf("Windows") >= 0) { return true; } return false; } public String getUserDir() { Object object = ptHashtable.get(USER_DIR); if(null ==object) { return null; } return object.toString(); } private void InitAllProperties() { Properties ps = System.getProperties(); Enumeration EP = ps.propertyNames(); ptHashtable = new HashMap<String, String>(); for(;EP.hasMoreElements();) { String pn = (String)EP.nextElement(); String pv = ps.getProperty(pn); ptHashtable.put(pn, pv); } } public static void main(String[] args) { String OSName = SystemProperties.newInstance().getOSName(); System.out.println(OSName); } }