package com.googosoft.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

/**
 * @author songyan
 * @date 2020年5月27日 下午3:33:20
 * @desc Properties文件读取
 */
public class PropertiesUtil {
    
    /**
     * 读取指定properties文件的指定属性值
     * @param propertiesFilePath
     * @param handlerClass
     * @return
     */
    public static String get(String propertiesFilePath, String key) {
        Properties prop = new Properties();
        try (InputStream in = new BufferedInputStream(new FileInputStream(propertiesFilePath));) {
            prop.load(in);
            return prop.getProperty(key);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定properties文件中第一个指定属性值的属性名
     * @param propertiesFilePath
     * @param value
     * @return
     */
    public static String getFirstKeyByValue(String propertiesFilePath, String value) {
        Properties prop = new Properties();
        try (InputStream in = new BufferedInputStream(new FileInputStream(propertiesFilePath));) {
            prop.load(in);
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                String itemKey = it.next();
                String itemValue = prop.getProperty(itemKey);
                if (value != null && value.equals(itemValue)) {
                    return itemKey;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }
}

 

posted on 2020-05-28 07:57  song.yan  阅读(215)  评论(0)    收藏  举报