Android Properties 使用实例

       Android应用开发的过程中有的时候我们可能会用到.properties文件来写一些配置信息(例如服务器的IP,端口号,APP应用更新的URL等等)。下面就对Android 应用中操作Properties文件做一个简单的封装(没什么技术含量) .properties文件放置在assetes文件夹下面。

简单的类图如下

这里写图片描述

主要的操作都在BasePropertiesConfig文件中完成,代码如下

public abstract class BasePropertiesConfig implements BasePropertiesControl {

    private final Properties mProps = new Properties();

    protected abstract Context getContext();

    protected abstract String getPropertyFileName();

    protected BasePropertiesConfig() {
        initialize();
    }

    private void initialize() {
        Context context = getContext();
        InputStream in = null;
        try {
            AssetManager assetManager = context.getAssets();
            in = assetManager.open(getPropertyFileName());
            mProps.load(in);
        } catch (IOException e) {
            Log.e("BasePropertiesConfig", "Cannot open: " + getPropertyFileName());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    @Override
    public boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    @Override
    public boolean getBoolean(String key, boolean defVal) {
        return Boolean.parseBoolean(mProps.getProperty(key, Boolean.toString(defVal)));
    }

    @Override
    public int getInteger(String key) {
        return getInteger(key, 0);
    }

    @Override
    public int getInteger(String key, int defVal) {
        return Integer.parseInt(mProps.getProperty(key, Integer.toString(defVal)));
    }

    @Override
    public short getShort(String key) {
        return getShort(key, 0);
    }

    @Override
    public short getShort(String key, int defVal) {
        return Short.parseShort(mProps.getProperty(key, Integer.toString(defVal)));
    }

    @Override
    public long getLong(String key) {
        return getLong(key, 0);
    }

    @Override
    public long getLong(String key, int defVal) {
        return Long.parseLong(mProps.getProperty(key, Integer.toString(defVal)));
    }

    @Override
    public String getString(String key) {
        return mProps.getProperty(key);
    }

    @Override
    public String getString(String key, String defVal) {
        return mProps.getProperty(key, defVal);
    }
}

顺带附上一个实例(很简单的很简单的)

发布了137 篇原创文章 · 获赞 197 · 访问量 34万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览