1.首先展示下Properties解析过程
public static void main(String[] args) {
//输入流
InputStream is = PropertiesParser.class.
getResourceAsStream("/first.properties");
//创建Properties对象
Properties properties = new Properties();
try {
//加载文件
properties.load(is);
//获取所有的键
Enumeration<Object> keys = properties.keys();
while(keys.hasMoreElements()) {
//遍历键集合,得到key 和 value输出
String key = (String) keys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ":" + value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
2.properties工具化
package com.mec.excise;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertiesParse {
//properties对象只需要一份即可所以设置为静态成员。
private static Properties properties;
//将所有的键值对放在map里方便查找,加快程序运行速度。
private static Map<String, String> map;
static {
properties = new Properties();
map = new HashMap<String, String>();
}
//加载文件
public static void loading(String path){
InputStream is = Class.class.getResourceAsStream(path);
loading(is);
}
//重载加载文件
public static void loading(InputStream is){
try {
properties.load(is);
PutSet();
} catch (IOException e) {
e.printStackTrace();
}
}
//将所有的键,值,放到map里
private static void PutSet() {
Enumeration<Object> em = properties.keys();
while(em.hasMoreElements()) {
String key = (String) em.nextElement();
String value = properties.getProperty(key);
map.put(key, value);
}
}
//通过键得到对应的值
public static String getvalue(String key) {
return map.get(key);
}
//得到键集合。
public static Set<String> KeySet() {
return map.keySet();
}
}
3.展示应用,只需两三行代码就完成解析。
package com.mec.test;
import com.mec.excise.PropertiesParse;
public class PropertiesParseTest {
public static void main(String[] args) {
new PropertiesParse();
PropertiesParse.loading("/first.properties");
System.out.println(PropertiesParse.getvalue("id"));
}
}