1. Java Properties 类
Properties(Java.util.Properties)主要用于读取java的配置文件,通常读取.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
2. 成员方法
Properties主要包含以下几个成员方法:
- load ( InputStream inStream)
用于从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。 - getProperty ( String key)
从properties对象中去获取key对于的value值。 - setProperty ( String key, String value)
在properties对象中去设置key/value值。
3. 读取Properties文件
load ( InputStream inStream)方法需要传入一个InputStream 类型的参数,该参数可以使用FileInputStream(new File(String path))去获得,更常用的是通过class.getResourceAsStream(String path)去获得。
4. 实例
public class PropsUtil {
private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);
public static Properties loadProps(String propsPath){
Properties properties = new Properties();
InputStream is = null;
try {
if(StringUtil.isEmpty(propsPath)){
throw new IllegalArgumentException();
}
is = PropsUtil.class.getResourceAsStream(propsPath);
if(is != null){
properties.load(is);
}
} catch (Exception e) {
logger.error("加载文件出错", e);
throw new RuntimeException(e);
} finally {
try {
if(is != null){
is.close();
}
} catch (Exception e) {
logger.error("释放资源出错", e);
}
}
return properties;
}
public static String getValue(Properties properties, String key){
return properties.getProperty(key);
}
public static String getValue(Properties properties, String key, String defaultValue){
String value = defaultValue;
if(properties.containsKey(key)){
value = properties.getProperty(key);
}
return value;
}
}