工具(一):properties配置文件读取工具类

来源:互联网 发布:淘宝仓管 编辑:程序博客网 时间:2024/05/22 14:33

本文着重介绍properties配置文件的解析使用。闲言少叙,直接上工具:

package com.wdy.tools.utils;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;/** *Properties配置文件处理工具 * @author wdy */public class PropertiesUtil {    // 静态块中不能有非静态属性,所以加static    private static Properties prop = null;    //静态块中的内容会在类别加载的时候先被执行    static {        try {            prop = new Properties();            // prop.load(new FileInputStream(new File("C:\\jdbc.properties")));            prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("configs/jdbc.properties"));        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    //静态方法可以被类名直接调用    public static String getValue(String key) {        return prop.getProperty(key);    }}
以上就是PropertiesUtil工具类了,具体用法:

假设你的配置文件是这样的:

driver = com.mysql.jdbc.Driverurl = jdbc:mysql://localhost:3306/myorclusername = rootpassword = root
那么你可以这样读取你的配置信息:

String driver = PropertiesUtil.getValue("driver");System.out.println(driver);//输出结果:com.mysql.jdbc.Driver
这样你就把你的配置信息读取成功了。是不是很简单。



原创粉丝点击