properties工具类

package com.antke;

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

public class PropertiesConfig {
    //配置文件名称
    private String properiesName = "4tong-houseWeb.properties";
    //构造函数
    public PropertiesConfig(String fileName) {
        this.properiesName = fileName;
    }
    /**
     * 按key获取值
     * @param key
     * @return
     */
    public String readProperty(String key) {
        String value = "";
        InputStream is = null;
        try {
            is = PropertiesConfig.class.getClassLoader().getResourceAsStream(properiesName);
            Properties p = new Properties();
            p.load(is);
            value = p.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return value;
    }
    /**
     * 获取整个配置信息
     * @return
     */
    public Properties getProperties() {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = PropertiesConfig.class.getClassLoader().getResourceAsStream(properiesName);
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p;
    }
    /**
     * key-value写入配置文件
     * @param key
     * @param value
     */
    public void writeProperty(String key, String value) {
        InputStream is = null;
        OutputStream os = null;
        Properties p = new Properties();
        try {
            is = new FileInputStream(properiesName);
            p.load(is);
            os = new FileOutputStream(properiesName);

            p.setProperty(key, value);
            p.store(os, key);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
                if (null != os)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        PropertiesConfig p = new PropertiesConfig("4tong-houseWeb.properties");
        System.out.println(p.getProperties().get("switching.dataSource"));
        System.out.println(p.readProperty("switching.dataSource"));
//        PropertiesConfig q = new PropertiesConfig("4tong-houseWeb.properties");
//        q.writeProperty("myUtils", "liu");
    }

}

 

posted @ 2021-07-19 15:51  一步一高  阅读(119)  评论(0编辑  收藏  举报