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);
    }
}

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

你可能感兴趣的:(android,android,properties,properties,配置文件)