您的位置:首页 > 运维架构

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

2017-05-26 22:05 405 查看
本文着重介绍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.Driver
url = jdbc:mysql://localhost:3306/myorcl
username = root
password = root 那么你可以这样读取你的配置信息:
String driver = PropertiesUtil.getValue("driver");
System.out.println(driver);//输出结果:com.mysql.jdbc.Driver 这样你就把你的配置信息读取成功了。是不是很简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  properties util 工具类