java 读取 properties文件

package com.aliyun;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyConfigurer{
    
    private static Properties props;
    static{
        loadProps();
    }

    synchronized static private void loadProps(){
        props = new Properties();
        InputStream in = null;
        try {
            in = PropertyConfigurer.class.getClassLoader().getResourceAsStream("AliyunConfig.properties");
            props.load(in);
        }
        catch(FileNotFoundException e)
        {
            System.err.println("Aliyunconfig.properties文件未找到");
        }
        catch (IOException e)
        {
             System.err.println("io操作异常");
        }
        finally
        {
            try{
                if(null != in) {
                    in.close();
                }
            }
            catch(IOException e)
            {
                System.err.println("Aliyunconfig.properties文件流关闭出现异常");
            }
        }
        System.err.println("properties文件内容:" + props);
    }

    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
    
    public static void main(String[] args) {
        System.out.println(PropertyConfigurer.getProperty("endpoint"));
    }
}

 

posted @ 2016-12-23 14:09  he0xff  阅读(159)  评论(0编辑  收藏  举报