📄 readconfig.java
字号:
package accp.factory;
import java.io.FileInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ReadConfig {
private static ReadConfig config = new ReadConfig();
private ReadConfig() {}
public static ReadConfig getInstance() {
return config;
}
/**
* 得到配置文件的路径
*
* @throws Exception
* @return String
*/
private static String getPath() {
URL url = ReadConfig.class.getClassLoader().getResource("");
String xml = url.getPath() + "/config.xml";
return xml;
}
public void analyse() throws Exception{
String file = this.getClass().getClassLoader().getResource(".").getPath()+"/config.xml";
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new FileInputStream(file));
Element root = doc.getRootElement(); //conf
List<Element> childlist1 = root.getChildren();
for(Element e1 : childlist1) {
List<Element> childlist2 = e1.getChildren();
for(Element e2 : childlist2) {
System.out.println(e2.getName()+"="+e2.getText());
}
}
}
/**
* 读取配置文件
*
* @return Properties
*/
public Map<String,String> readFromXML() {
Map<String,String> map = new HashMap<String,String>();
SAXBuilder sb = new SAXBuilder();
try {
// 从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
Document doc = sb.build(new FileInputStream(getPath()));
//得到根元素--conf
Element root = doc.getRootElement();
//得到根元素所有子元素的集合--database/dao
List root1 = root.getChildren();
List sub1 = null;
for (Iterator iter1 = root1.iterator(); iter1.hasNext();) {
Element rootEle = (Element) iter1.next();
//再次得到子元素的孙元素集合,即database/dao下的子元素
sub1 = rootEle.getChildren();
//if ("dao".equals(rootEle.getName())) {
for (Iterator iter2 = sub1.iterator(); iter2.hasNext();) {
Element subEle = (Element) iter2.next();
map.put(subEle.getName(), subEle.getText());
//System.out.println(subEle.getName() + "=" + subEle.getText());
}
//}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
ReadConfig conf = new ReadConfig();
conf.readFromXML();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -