Java获取系统环境变量的方法

java中获取环境变量:

STEPS:
1. Try to get environment from JVM system property
m_env = System.getProperty(“env”);
2. Try to get environment from file "server.properties"
m_env = m_serverProperties.getProperty(“env”);
3. Try to get environment from OS environment variable
m_env = System.getenv(“ENV”);

public class EnvUtil {

    private static final String SERVER_PROPERTIES_LINUX = "/etc/sys_env.ini";
    private static final String SERVER_PROPERTIES_WINDOWS = "C:/opt/settings/server.properties";

    private static Properties m_serverProperties = new Properties();
    private static String m_env;

    private static class LazyHolder{
        // final 为了防止内部误操作,cglib的代理模式以子类方式实现,可能会修改该值
        private static final EnvUtil INSTANCE = new EnvUtil();
    }

    // 提供静态方法获取实例
    // final 确保别人不能覆盖
    public static final EnvUtil getInstance() {
        return LazyHolder.INSTANCE;
    }

    private EnvUtil() {
        initialize();
    }

    public String getEnv(){
        return m_env;
    }
    
    private static void initialize(){
        try {
            String path = Utils.isOSWindows() ? SERVER_PROPERTIES_WINDOWS : SERVER_PROPERTIES_LINUX;

            File file = new File(path);
            if (file.exists() && file.canRead()) {
                FileInputStream fis = new FileInputStream(file);
                initialize(fis);
            }else{
                initialize(null);
            }

        } catch (Throwable ex) {

        }
    }

    private static void initialize(InputStream in) {
        try {
            if (in != null) {
                try {
                    m_serverProperties.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
                } finally {
                    in.close();
                }
            }
            initEnvType();
        } catch (Throwable ex) {
            log.error("获取系统环境变量错误:"+ex.getMessage());
        }
    }

    private static void initEnvType() {

        // 1. Try to get environment from JVM system property
        m_env = System.getProperty("env");
        if (!Utils.isBlank(m_env)) {
            m_env = m_env.trim();
            return;
        }

        // 2. Try to get environment from file "server.properties"
        m_env = m_serverProperties.getProperty("env");
        if (!Utils.isBlank(m_env)) {
            m_env = m_env.trim();
            return;
        }

        // 3. Try to get environment from OS environment variable
        m_env = System.getenv("ENV");
        if (!Utils.isBlank(m_env)) {
            m_env = m_env.trim();
            return;
        }

        m_env = null;
        // 4. return environment to null.
    }
}

你可能感兴趣的:(java基础)