Properties 配置使用

  • Properties 有点类似 Android 中的 SP。
  • Properties 创建一个文件,然后对文件进行读写操作。

具体操作

1. 创建工具类

public class PropertiesUtil {

    private static final String PROP_PATH = 文件路径+文件名;

    /**
     * 得到config.properties配置文件中的所有配置属性
     *
     * @return Properties对象
     */
    public static Properties loadConfig() {
        Properties properties = new Properties();
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(PROP_PATH);
            properties.load(inputStream);
        } catch (Exception e) {
            LogUtil.e(e);
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LogUtil.e(e);
                }
            }
        }
        return properties;
    }

    /**
     * 保存配置文件
     */
    public static void saveConfig(Properties properties) {
        FileOutputStream outputStream = null;
        try {
            File fil = new File(PROP_PATH);
            if (!fil.exists()) {
                fil.createNewFile();
            }
            outputStream = new FileOutputStream(fil);
            properties.store(outputStream, "");
        } catch (Exception e) {
            LogUtil.e(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    LogUtil.e(e);
                }
            }
        }
    }
}

2. 工具类的使用

//取数据
Properties properties = PropertiesUtil.loadConfig();
String value = properties.getProperty("key");
//存数据
Properties properties = properties = new Properties();
properties.put("key", value);
PropertiesUtil.saveConfig(properties);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容