PropertiesUtils

2019-06-20  本文已影响0人  吕小凯

PropertiesUtils 工具类

package com.redxun.apollo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesUtils {

    public static final Properties p = new Properties();
    public static String path = null;

    /**
     * 通过类装载器 初始化Properties
     */
    public static void init(String envrionment) {
        //转换成流
        InputStream is = null;
        path = PropertiesUtils.class.getClassLoader().getResource("config/redxun.properties").getPath();
        try {
            is = new FileInputStream(path);
            //从输入流中读取属性列表(键和元素对)
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过key获取value
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        return p.getProperty(key);
    }

    /**
     * 修改或者新增key
     *
     * @param key
     * @param value
     */
    public static void update(String key, String value) {
        p.setProperty(key, value);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            //将Properties中的属性列表(键和元素对)写入输出流
            p.store(oFile, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 循环所有key value
     */
    public static void list() {
        Enumeration en = p.propertyNames(); //得到配置文件的名字
        while (en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = p.getProperty(strKey);
        }
    }

    /**
     * 清空配置
     */
    public static void remove() {
        Enumeration en = p.propertyNames(); //得到配置文件的名字
        while (en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            update(strKey, "");
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读