先建立一个properties文件。
通过做工具对properties文件进行解析:
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesParser {
//只需一份即可,为的是即使在主函数中new多个对象,也只生成一个pool,
//把所有的键值对都存在这同一个MAP中
private static final Map<String, String> pool;
static {
pool = new HashMap<String, String>();
}
public PropertiesParser() {
}
public void loadProperties(String path) {
InputStream is = Class.class.getResourceAsStream(path);
Properties properties = new Properties();
try {
//这里会出现异常,只需要try/catch就好
properties.load(is);
Enumeration<Object> keys = properties.keys();
while(keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = properties.getProperty(key);
pool.put(key, value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getValue(String key) {
return pool.get(key);
}
}
public static void main(String[] args) {
PropertiesParser propertiesOne = new PropertiesParser();
propertiesOne.loadProperties("/oneProperty.properties");
String name = propertiesOne.getValue("name");
String sex = propertiesOne.getValue("sex");
String id = propertiesOne.getValue("id");
String birth = propertiesOne.getValue("birth");
System.out.println("name : " + name + "\nsex : "
+ sex + "\nid : " + id + "\nbirth : " + birth);
}
执行结果: