Java读取Properties文件

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;


public class PropertieUtil {
    private static Logger logger = Logger.getLogger(PropertieUtil.class);
    private PropertieUtil() {
    }
    /**
     * 读取配置文件某属性
     */
    public static String readValue(String filePath, String key) {
        Properties props = new Properties();
        try {
            //从src路径下读取
            InputStream in = PropertieUtil.class.getClassLoader().getResourceAsStream(filePath);
            props.load(in);
            String value = props.getProperty(key);
            return value;
        } catch (Exception e) {
            logger.error(e);
            return null;
        }
    }
    /**
     * 打印配置文件全部内容(filePath,配置文件名,如果有路径,props/test.properties)
     */
    public static void readProperties(String filePath) {
        Properties props = new Properties();
        try {
            //从src路径下读取
            InputStream in = PropertieUtil.class.getClassLoader().getResourceAsStream(filePath);
            props.load(in);
            Enumeration<?> en = props.propertyNames();
            // 遍历打印
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String Property = props.getProperty(key);
                logger.info(key + ":" + Property);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
    /**
     * 将值写入配置文件
     */
    public static void writeProperties(String fileName, String parameterName, String parameterValue) throws Exception {
        // 本地测试特别注意,如果是maven项目,请到\target目录下查看文件,而不是源代码下
        // 注意路径不能加 / 了,加了则移除掉
        if (fileName.startsWith("/"))
            fileName.substring(1);
        String filePath = PropertieUtil.class.getResource("/").getPath()+fileName;
        // 获取配置文件
        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        in.close();
        OutputStream out = new FileOutputStream(filePath);
        // 设置配置名称和值
        pps.setProperty(parameterName, parameterValue);
        // comments 等于配置文件的注释
        pps.store(out, "Update " + parameterName + " name");
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception {
        readProperties("jdbc.properties");
//      logger.info(readValue("jdbc.properties", "JAVABLOG_WRITE_URL"));
//      writeProperties("test.properties", "test", "test");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值