All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.opslab.util.PropertiesUtil Maven / Gradle / Ivy

package com.opslab.util;


import java.io.*;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 提供一些常用的属性文件相关的方法
 */
public class PropertiesUtil {

    /**
     * 从系统属性文件中获取相应的值
     *
     * @param key key
     * @return 返回value
     */
    public static String key(String key) {
        return System.getProperty(key);
    }

    /**
     * 根据Key读取Value
     *
     * @param filePath 属性文件
     * @param key      需要读取的属性
     */
    public static String GetValueByKey(String filePath, String key) {
        Properties pps = new Properties();
        try (InputStream in = new BufferedInputStream(new FileInputStream(filePath))) {
            pps.load(in);
            return pps.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取Properties的全部信息
     *
     * @param filePath 读取的属性文件
     * @return 返回所有的属性 key:value<>key:value
     */
    public static String GetAllProperties(String filePath) throws IOException {
        Properties pps = new Properties();
        String     str = "";
        try (InputStream in = new BufferedInputStream(new FileInputStream(filePath))) {
            pps.load(in);
            Enumeration en = pps.propertyNames();
            while (en.hasMoreElements()) {
                String strKey = (String) en.nextElement();
                String strValue = pps.getProperty(strKey);
                str += strKey + ":" + strValue + "<>";
            }
        }
        return str.substring(0, str.lastIndexOf("<>"));
    }

    /**
     * 写入Properties信息
     *
     * @param filePath 写入的属性文件
     * @param pKey     属性名称
     * @param pValue   属性值
     */
    public static void WriteProperties(String filePath, String pKey, String pValue) throws IOException {
        Properties props = new Properties();

        props.load(new FileInputStream(filePath));
        // 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
        // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream fos = new FileOutputStream(filePath);
        props.setProperty(pKey, pValue);
        // 以适合使用 load 方法加载到 Properties 表中的格式,
        // 将此 Properties 表中的属性列表(键和元素对)写入输出流
        props.store(fos, "Update '" + pKey + "' value");

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy