properties配置文件,是一种基于键值对的简单配置文件
xml配置文件,是一种树的结构,可以处理各种各样定义好的情况的配置文件,在properties配置文件中就没有办法实现了。
1、properties实例:
public class PropertyParser {
private Properties properties = null;
public PropertyParser(String propertyFileName) {
properties = new Properties();
try {
ClassLoader c = PropertyParser.class.getClassLoader();
properties.load(c.getResourceAsStream(propertyFileName));
} catch (FileNotFoundException e) {
e.getLocalizedMessage();
} catch (IOException e) {
e.getLocalizedMessage();
}
}
public String getProperty(String key) {
if (properties == null) {
return null;
}
return properties.getProperty(key);
}
}
2、xml实例:
xml文件的读取有很多方法这里我是用dom4j读取的现在dom4j用的比较多因为dom4j功能比较强大
使用时要倒入dom4j的jar包
!!!注意:在使用dom4j提供的selectNodes等深度查询方法时要倒入jaxen的jar包
(1)读取xml(深度查询+遍历)
/**
* 叶子节点模板类
* @author JiangGengChao
*/
public class Leaf {
private String xpath = null;
private String value = null;
public String getXpath() {
return xpath;
}
public void setXpath(String xpath) {
this.xpath = xpath;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Leaf(String xpath, String value) {
this.xpath = xpath;
this.value = value;
}
}
/**
* 叶子节点遍历结果集
*/
private static List<Leaf> elemList = new ArrayList<Leaf>();
/**
* 查询xml
*/
public void getdom() {
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("test.xml"));
Element root = document.getRootElement();
//深度查询
@SuppressWarnings("unchecked")
List<Element> ele = root.selectNodes("//test2.1");
System.out.println(ele.get(0).getText());
System.out.println("-------我是分界线-------")
//遍历
getElementList(root);
//显示遍历结果
StringBuffer sb = new StringBuffer();
for (Iterator<Leaf> it = elemList.iterator(); it.hasNext();) {
Leaf leaf = it.next();
sb.append(leaf.getXpath()).append(" = ").append(leaf.getValue()).append("\n");
}
System.out.println(sb);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 递归遍历方法
* @param element
*/
public void getElementList(Element element) {
@SuppressWarnings("unchecked")
List<Element> elements = element.elements();
if (elements.size() == 0) {
//没有子元素
String xpath = element.getPath();
String value = element.getTextTrim();
elemList.add(new Leaf(xpath, value));
} else {
//有子元素
for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
Element elem = it.next();
//递归遍历
getElementList(elem);
}
}
}
(2)写入
public void saveDocument(Document doc,String filepath){
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = null;
try {
writer = new XMLWriter(new FileWriter(new File(filepath)), format);
writer.write(doc);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}