这个应该是很基础的了,我这里介绍2种读取config文件的方式,一种是用java的Properties, 另外一种是读取Yaml文件格式
1.java的properties读取
private Properties properties = null; public PropUtil(String path) { initialize(path); } private void initialize(String path) { FileInputStream is = null; try { is = new FileInputStream(new File(path)); } catch (Exception e) { e.printStackTrace(); } if (is == null) { return; } properties = new Properties(); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (Exception e) { e.printStackTrace(); } } } public int size(){ return properties.size(); } public String get(String key) { String keyValue = null; if (properties.containsKey(key)) { keyValue = (String) properties.get(key); } return keyValue; }
示例读取:
public PropUtil projprops = new PropUtil("./config/youribm.properties"); protected String automasterUrl = projprops.get("youribm.automasterUrl");
2. Yaml的方式读取,就是转换成HashMap数据格式
private String yamlFilePath; private HashMap<String, HashMap<String, String>> elementsMap = new HashMap<String, HashMap<String, String>>(); public YamlCreate(String yamlFilePath) { this.yamlFilePath = yamlFilePath; loadYaml(); } private void loadYaml() { try { elementsMap = Yaml.loadType(new FileInputStream(yamlFilePath),HashMap.class); } catch (Exception e) { e.printStackTrace(); } } public HashMap<String, HashMap<String, String>> getElementsMap() { return elementsMap; }
示例读取:
MteSenseLocator config = new MteSenseLocator("./config/mtesenseexample.yaml");
String locatorString = elementsMap.get(key).get(value);
String url = config.getLocator("urlfield")