美文网首页
PropertiesUtils

PropertiesUtils

作者: 吕小凯 | 来源:发表于2019-06-20 14:14 被阅读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, "");
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:PropertiesUtils

          本文链接:https://www.haomeiwen.com/subject/vsuyqctx.html