*.properties文件通常以键值对的方式存贮配置文件信息,Properties 实际上是继承了hashtable,实现了Map接口,对其内容的读取实际上是通过IO对文件进行扫描读取,接下来就是本人整理的可配置的properties文件读取方式。
1、文件加载读取类(PropertiesLoader)
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertiesLoader {
private final static Logger LOG = Logger.getLogger(PropertiesLoader.class);
public static Properties properties;
private static String filePath = "src/resource/";
public PropertiesLoader(String fileName) {
FileInputStream in = null;
try{
properties = new Properties();
in = new FileInputStream(filePath+fileName);
properties.load(in);
}catch(Exception e){
e.printStackTrace();
LOG.error("配置文件解析错误");
}finally{
if(in != null){
try{
in.close();
}catch(Exception e){
e.printStackTrace();
LOG.error("文件输入流关闭错误");
}
}
}
}
public String getProperty(String key) {
String value = properties.getProperty(key);
return value;
}
}
2、常量类读取参数(ConfigConstant)
public class ConfigConstant {
// 加载数据库配置信息
private static PropertiesLoader dbProperties = new PropertiesLoader("dbconfig.properties");
// 读取配置文件参数
public static String dbNbDriver = dbProperties.getProperty("driverClassName");
public static String dbNbUrl = dbProperties.getProperty("url");
public static String dbNbUser = dbProperties.getProperty("username");
public static String dbNbPassword = dbProperties.getProperty("password");
}
3、配置文件(dbconfig.properties)
url=jdbc:mysql://localhost:3306
driverClassName=com.mysql.jdbc.Driver
username=root
password=123456
filters=stat
maxActive=20
initialSize=1
maxWait=60000
minIdle=1
timeBetweenEvictionRunsMillis=3000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT now();
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
maxPoolPreparedStatementPerConnectionSize=20
通过这样的配置,java类可以直接用ConfigConstant.参数名的方式引用配置文件的参数。