Java工具类--读取Properties文件

package com.skr.mdm.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.InputStreamReader;
import java.util.*;

/**
 * 读取配置文件的工具类
 */

public class PropertiesUtil {

    private Properties props;

    public PropertiesUtil(String fileName) {
        readProperties(fileName);
    }

    /**
     * 加载配置文件
     *
     * @param fileName
     */
    private void readProperties(String fileName) {
        try {
            props = new Properties();
            InputStreamReader inputStream = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream(fileName), "UTF-8");
            props.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key读取对应的value
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return props.getProperty(key);
    }

    /**
     * 得到所有的配置信息
     *
     * @return
     */
    public Map<String, String> getAll() {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<?> enu = props.propertyNames();
        while (enu.hasMoreElements()) {
            String key = (String) enu.nextElement();
            String value = props.getProperty(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 得到所有的配置信息
     *
     * @return
     */
    public List<String> keyList() {
        List<String> keyList = new ArrayList<>() ;
        Enumeration<?> enu = props.propertyNames();
        while (enu.hasMoreElements())
            keyList.add((String) enu.nextElement()) ;
        return keyList;
    }

    public static void main(String[] args) {
        PropertiesUtil propertiesUtil = new PropertiesUtil("MDMTag.properties") ;
        System.out.println(JSONObject.fromObject(propertiesUtil.getAll())) ;
        System.out.println(JSONArray.fromObject(propertiesUtil.keyList())) ;
    }

}

转至:https://blog.csdn.net/frankcheng5143/article/details/50432820?locationNum=10

猜你喜欢

转载自blog.csdn.net/wkh___/article/details/82853429