Android 使用Properties配置文件

        相信各位在进行Android开发过程中会遇见有时需要把一些配置信息保存到本地的需求,当然Android中有SharedPreferences可以提供给我们使用,但是知道另一种方法也不错,是吧。以下是针对使用Properties的一个类,调用简单new传入自定义文件路径路径即可。

       文件格式为一个参数一行,后面会有具体生成格式。

import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class AndroidProperties {
    private String filePath;
    private File file;

    public AndroidProperties(String filePath) {
        this.filePath = filePath;
        if(TextUtils.isEmpty(filePath)){
            throw new NullPointerException("filePath is null");
        }
        file = new File(filePath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            file.getParentFile().mkdirs();
        }
    }

    private Properties get() {
        FileInputStream fis = null;
        Properties props = new Properties();
        try {
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                file.getParentFile().mkdirs();
            }
            fis = new FileInputStream(file);
            props.load(fis);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(null != fis){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return props;
    }

    /**
     * 对外提供的get方法
     * @param key
     * @return
     */
    public String get(String key) {
        Properties props = get();
        return (props != null) ? props.getProperty(key) : null;
    }

    private void setProps(Properties p) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            p.store(fos, null);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(null != fos){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 对外提供的保存key value方法
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        Properties props = get();
        props.setProperty(key, value);
        setProps(props);
    }

    /**
     * 对外提供的删除方法
     * @param key
     */
    public void remove(String... key) {
        Properties props = get();
        for (String k : key) {
            props.remove(k);
        }
        setProps(props);
    }
}


版权声明:本文为yzy1226466341原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。