java的配置文件除了xml外还可以是properties文件,properties文件的文件格式如下,由一个个键值对组成:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/dbname?autoReconnect=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
jdbc.maxIdle=2
读取properties文件的方法变化一般不大,所以在这里可以写一个工具类:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesUtil {
private static String defaultPropertyFilePath = "test.properties";
private static Map<String,Properties> ppsMap = new HashMap<String,Properties>();
/**
* 读取默认文件的配置信息,读key返回value
* @param key
* @return value
* @throws FileNotFoundException
*/
public static final String getPropertyValue(String key) throws FileNotFoundException {
Properties pps = getPropertyFile(defaultPropertyFilePath);
return pps == null ? null : pps.getProperty(key);
}
/**
* 传入filePath读取指定property文件,读key返回value
* @param propertyFilePath
* @param key
* @return value
* @throws FileNotFoundException
*/
public static String getPropertyValue(String propertyFilePath,String key) throws FileNotFoundException {
if(propertyFilePath == null) {
propertyFilePath = defaultPropertyFilePath;
}
Properties pps = getPropertyFile(propertyFilePath);
return pps == null ? null : pps.getProperty(key);
}
/**
* 根据path返回property文件,并保存到HashMap中,提高效率
* @param propertyFilePath
* @return
* @throws FileNotFoundException
*/
public static Properties getPropertyFile(String propertyFilePath) throws FileNotFoundException {
if(propertyFilePath == null) {
return null;
}
Properties pps = ppsMap.get(propertyFilePath);
if(pps == null) {
InputStream in = new BufferedInputStream(new FileInputStream(propertyFilePath));
pps = new Properties();
try {
pps.load(in);
} catch (IOException e) {
e.printStackTrace();
}
ppsMap.put(propertyFilePath, pps);
}
return pps;
}
}