介绍几个Properties类里面的常用函数:
它提供了几个主要的方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
对了Properties类是继承HashMaptable的,可能与HashMap和HashTable所存的键和值不能为空有关
假设配置文件,config.properties。在类加载路径下,文件中的key,value格式如下:
jdbc.url=jdbc:mysql://10.129.156.29:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=test
jdbc.password=123456
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import com.thinry.commons.utils.log.Log;
public class PropertiesUtils {
/**
* read properties file and return Map
* @param fileName
* @param wantKeyToValue
* @return
*/
public static Map<String, String> readPropertiesAndReturnMap(String fileName, boolean wantKeyToValue) {
Map<String, String> mapRet1 = null;
try {
Properties props = new Properties();
ClassPathResource classPathResource = new ClassPathResource(fileName);//去类加载路径下加载配置文件。
InputStream in = classPathResource.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in, "UTF-8");
props.load(inputStream);
mapRet1 = returnMap(props, wantKeyToValue);
} catch (IOException e) {
Log.error("PropertiesUtils readPropertiesAndReturnMap Exception", e);
} catch (Exception e) {
Log.error("PropertiesUtils readPropertiesAndReturnMap Exception", e);
}
return Collections.unmodifiableMap(mapRet1);// 返回不可改变的map,数据装载后就不需要改变了,改变这个map中的数据会报UnsupportedOperationException。
}
/**
* return Map for properties files
* @param propsTemp
* @param wantKeyToValue
* @return
*/
private static Map<String, String> returnMap(Properties propsTemp, boolean wantKeyToValue) {
Map<String, String> map = new HashMap<String, String>();
Enumeration<?> enu = propsTemp.propertyNames();
while (enu.hasMoreElements()) {
String key = (String) enu.nextElement();
String value = propsTemp.getProperty(key);
if (wantKeyToValue) {
map.put(key, value);
} else {
map.put(value, key);
}
}
return map;
}
}