1. 程式人生 > >讀取配置檔案 properties類工具

讀取配置檔案 properties類工具

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class UtilsProperties {

private static Logger log = LoggerFactory.getLogger(UtilsProperties.class);


/**
* 根據檔案路徑,key值讀取對應value
* @param path
* @param key
* @return
*/
public static String readProperties(String path,String key){
    long mStart = System.currentTimeMillis();
    Properties prop = new Properties();
    try {
        InputStream is = new BufferedInputStream(new FileInputStream(path));
        try {
            prop.load(is);
            long mEnd = System.currentTimeMillis();
            log.info("檔案讀取成功,共耗時:{}",mEnd-mStart);
            return prop.getProperty(key);
        } catch (IOException e) {
            log.debug("檔案已獲取,但讀取異常");
            e.printStackTrace();

        }

    } catch (FileNotFoundException e) {

        log.debug("獲取檔案異常,可能該檔案不存在");
        e.printStackTrace();
    }
    return null;
}

/**
* 根據檔案路徑,獲取配置檔案所有鍵值對
* @param path
* @return
*/
public static Map<String,String> readAllProperties(String path){
    Map<String,String> map = new HashMap<String,String>();
    Properties prop = new Properties();
    try {
        InputStream is = new BufferedInputStream(new FileInputStream(path));
        try {
            prop.load(is);
            Enumeration<?> en = prop.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = prop.getProperty(key);
                map.put(key, value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return map;
}

/**
* 將key和value寫入指定配置檔案
* @param path
* @param key
* @param value
*/
public static void writeProperties(String path, String key, String value){
    Properties prop = new Properties();
    try {
        InputStream is = new BufferedInputStream(new FileInputStream(path));
        try {
            prop.load(is);
            OutputStream os = new FileOutputStream(path);
            prop.setProperty(key, value);
            prop.store(os, "Update " + key + " name");
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
//String value = UtilsProperties.readProperties("Test.properties","long");
//UtilsProperties.readAllProperties("Test.properties");
UtilsProperties.writeProperties("Test.properties","hahah","bbb");
}
}