一、properties文件
.properties配置文件是什么?
答:Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”
作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。
例如java应用通过JDBC连接数据库时,可以把数据库的配置写在配置文件 jdbc.properties:
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/user
user=root
password=123456
二、Properties类
java中提供了配置文件的操作类Properties类(java.util.Properties):
读取properties文件的通用方法:根据键得到value
/**
* 读取config.properties文件中的内容,放到Properties类中
* @param filePath 文件路径
* @param key 配置文件中的key
* @return 返回key对应的value
*/
public static String readConfigFiles(String filePath,String key) {
Properties prop = new Properties();
try{
InputStream inputStream = new FileInputStream(filePath);
prop.load(inputStream);
inputStream.close();
return prop.getProperty(key);
}catch (Exception e) {
e.printStackTrace();
System.out.println("未找到相关配置文件");
return null;
}
}
把配置文件以键值对的形式存放到Map中:
/**
* 把.properties文件中的键值对存放在Map中
* @param inputStream 配置文件(inputstream形式传入)
* @return 返回Map
*/
public Map<String, String> convertPropertityFileToMap(InputStream inputStream) {
try {
Properties prop = new Properties();
Map<String, String> map = new HashMap<String, String>();
if (inputStream != null) {
prop.load(inputStream);
Enumeration keyNames = prop.propertyNames();
while (keyNames.hasMoreElements()) {
String key = (String) keyNames.nextElement();
String value = prop.getProperty(key);
map.put(key, value);
}
return map;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
在XML配置文件中使用properties文件的键值作为变量化参数