关于java中遍历map、dom4j解析xml文件、加载properties文件

1. Map遍历
方法一:
    for (Object o : testMap.keySet()) {
       System.out.println("key=" + o + " value=" + testMap.get(o));
    }
方法二:
    Map map = new HashMap();
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
    }
2. dom4j解析
文件:test.xml
<root>
        <second secondName="i">
                <qq>信息一</qq>
                <www>
                        org.apache.commons.beanutils1
                </www>
         </second>
        <second secondName="ii">
                <qq>信息二</qq>
                <www>
                        org.apache.commons.beanutils2
                </www>
         </second>
</root>

java code
文件名:Testjava.java

String config_file = "test.xml";
String secondName = "";
String www= "";
Document document = null;
SAXReader saxReader = new SAXReader();
try {
    document = saxReader.read(Testjava.class.getResourceAsStream(config_file));
    Element secondElement = document.getRootElement();
    List<?> secondList = secondElement.elements();
    for(int i=0;i<secondList.size();i++){
        Element thirdElement = (Element) secondList.get(i);
        secondName = thirdElement.attributeValue("secondName ");
        www= thirdElement.element("www").getText().trim();
    }
} catch (DocumentException e) {
    e.printStackTrace();
}

3.load properties文件

InputStream is = this.getClass().getResourceAsStream(prop_file);
Properties dbProps = new Properties();
try {
    dbProps.load(is);
    System.out.println(dbProps.getProperty("ParameterName"));
} catch (IOException e) {
    e.printStackTrace();
}

4.PropertiesUtils
private static final String PATH_PROPERTIES_FILE = "properties/raspi.properties";
private static Properties prop = new Properties();

static {
try {
ClassLoader loader = PropertiesUtils.class.getClassLoader();
if (loader == null)
loader = ClassLoader.getSystemClassLoader();

URL url = loader.getResource(PATH_PROPERTIES_FILE);
prop.load(url.openStream());
} catch (Exception e) {
e.printStackTrace();
}
}

public static String getPropertieByKey(String key) {
String result = StringUtils.EMPTY;
try {
result = prop.getProperty(key);
} catch (Exception e) {
LOG.error("getPropertieByKey error. ", e);
}
return result;
}

你可能感兴趣的:(java,apache,xml,propertiesutils)