工具类——Android使用配置文件properties统一管理app的一些配置

来源:互联网 发布:cpu测温度软件 编辑:程序博客网 时间:2024/06/17 07:00

一、建立工具类ConfigUtils

public static HashMap readProperties(Context context){        HashMap<String,String> propertiesmap=new HashMap<String, String>();        Properties properties=new Properties();        try {            //assets目录下的config.properties配置文件            InputStream inputStream=context.getClassLoader().getResourceAsStream("assets/config.properties");            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));            properties.load(bufferedReader);            Iterator iterator=properties.entrySet().iterator();            while(iterator.hasNext()){                Map.Entry entry= (Map.Entry) iterator.next();                Object key=entry.getKey();                Object value=entry.getValue();                //把value值转换为utf-8编码的字符串,避免乱码                value = new String(value.toString().getBytes("UTF-8"));                propertiesmap.put(key.toString().trim(),value.toString().trim());            }            inputStream.close();            return propertiesmap;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

这里注意:assets/config.properties的文件位置 哈
这里写图片描述

我这里附带一个配置文件地址大家可下载看看。

二、使用步骤

1、IApplication初始化

  • 首先建立map存放文件中的key 和value
/**     * 保存从config.properties文件中的参数配置     */    public static HashMap<String,String> mPropertiesMap=new HashMap<String, String>();
  • onCreate()方法中new初始化
mPropertiesMap = ConfigUtils.readProperties(getApplicationContext());

2、获取字符使用

  String str = IApplication.mPropertiesMap.get("checkLogin");        LogUtils.e(str);

这样窝就可以根据配置文件来判断一些项目的不同了。

原创粉丝点击