Java開發(fā)中讀取XML與properties配置文件的方法
相關(guān)閱讀:
使用Ajax進(jìn)行文件與其他參數(shù)的上傳功能(java開發(fā))
1. XML文件:
什么是XML?XML一般是指可擴(kuò)展標(biāo)記語言,標(biāo)準(zhǔn)通用標(biāo)記語言的子集,是一種用于標(biāo)記電子文件使其具有結(jié)構(gòu)性的標(biāo)記語言。
2.XML文件的優(yōu)點(diǎn):
1)XML文檔內(nèi)容和結(jié)構(gòu)完全分離。 
2)互操作性強(qiáng)。 
3)規(guī)范統(tǒng)一。 
4)支持多種編碼。 
5)可擴(kuò)展性強(qiáng)。
3.如何解析XML文檔:
XML在不同的語言中解析XML文檔都是一樣的,只不過實(shí)現(xiàn)的語法不一樣,基本的解析方式有兩種,一種是SAX方式,是按照XML文件的順序一步一步解析。另外一種的解析方式DOM方式,而DOM方式解析的關(guān)鍵就是節(jié)點(diǎn)。另外還有DOM4J、JDOM等方式。本文介紹的是DOM、DOM4J方式與封裝成一個(gè)工具類的方式來讀取XML文檔。
4.XML文檔:
scores.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE students [ <!ELEMENT students (student+)> <!ELEMENT student (name,course,score)> <!ATTLIST student id CDATA #REQUIRED> <!ELEMENT name (#PCDATA)> <!ELEMENT course (#PCDATA)> <!ELEMENT score (#PCDATA)> ]> <students> <student id="11"> <name>張三</name> <course>JavaSE</course> <score>100</score> </student> <student id="22"> <name>李四</name> <course>Oracle</course> <score>98</score> </student> </students>
5.DOM方式解析XML
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
  //1.創(chuàng)建DOM解析器工廠
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  //2.由DOM解析器工廠創(chuàng)建DOM解析器
  DocumentBuilder db = dbf.newDocumentBuilder();
  //3.由DOM解析器解析文檔,生成DOM樹
  Document doc = db.parse("scores.xml");
  //4.解析DOM樹,獲取文檔內(nèi)容(元素 屬性 文本)
  //4.1獲取根元素scores
  NodeList scoresList = doc.getChildNodes();
  Node scoresNode = scoresList.item(1);
  System.out.println(scoresList.getLength());
  //4.2獲取scores中所有的子元素student
  NodeList studentList = scoresNode.getChildNodes();
  System.out.println(studentList.getLength());
  //4.3對每個(gè)student進(jìn)行處理
  for(int i=0;i<studentList.getLength();i++){
   Node stuNode = studentList.item(i);
   //System.out.println(stuNode.getNodeType());
   //輸出元素的屬性 id
   if(stuNode.getNodeType()==Node.ELEMENT_NODE){
    Element elem =(Element)stuNode;
    String id= elem.getAttribute("id");
    System.out.println("id------>"+id);
   }
   //輸出元素的子元素 name course score
   NodeList ncsList = stuNode.getChildNodes();
   //System.out.println(ncsList.getLength() );
   for(int j=0;j<ncsList.getLength();j++){
    Node ncs = ncsList.item(j);
    if(ncs.getNodeType() == Node.ELEMENT_NODE){
      String name = ncs.getNodeName();
      //String value = ncs.getFirstChild().getNodeValue();//文本是元素的子節(jié)點(diǎn),所以要getFirstChild
      String value = ncs.getTextContent();
      System.out.println(name+"----->"+value);
    }
   }
   System.out.println();
  }
 }
6.DOM4J方式解析XML文檔:
 public static void main(String[] args) throws DocumentException {
  //使用dom4j解析scores2.xml,生成dom樹
  SAXReader reader = new SAXReader();
  Document doc = reader.read(new File("scores.xml"));  
  //得到根節(jié)點(diǎn):students
  Element root = doc.getRootElement();  
  //得到students的所有子節(jié)點(diǎn):student
  Iterator<Element> it = root.elementIterator(); 
  //處理每個(gè)student
  while(it.hasNext()){
   //得到每個(gè)學(xué)生
   Element stuElem =it.next();
   //System.out.println(stuElem);
   //輸出學(xué)生的屬性:id
   List<Attribute> attrList = stuElem.attributes();
   for(Attribute attr :attrList){
    String name = attr.getName();
    String value = attr.getValue();
    System.out.println(name+"----->"+value);
   }
   //輸出學(xué)生的子元素:name,course,score
   Iterator <Element>it2 = stuElem.elementIterator();
   while(it2.hasNext()){
    Element elem = it2.next();
    String name = elem.getName();
    String text = elem.getText();
    System.out.println(name+"----->"+text);
   }
   System.out.println();
  } 
 }
當(dāng)然,無論我們是使用那種方式解析XML的,都需要導(dǎo)入jar包(千萬不要忘記)。
7.我自己的方式:
在實(shí)際開發(fā)的工程中,我們要善于使用工具類,將我們反復(fù)使用的功能封裝成一個(gè)工具類,所以,下面的方式就是我在開發(fā)的過程中使用的方式.
7.1什么是properties文件:
7.1.1 從結(jié)構(gòu)上講:
.xml文件主要是樹形文件。 
.properties文件主要是以key-value鍵值對的形式存在
7.1.2 從靈活的角度來說:
.xml文件要比.properties文件的靈活讀更高一些。
7.1.3 從便捷的角度來說:
.properties文件比.xml文件配置更加簡單。
7.1.4 從應(yīng)用程度上來說:
.properties文件比較適合于小型簡單的項(xiàng)目,因?yàn)?xml更加靈活。
7.2自己的properties文檔:
在我自己的項(xiàng)目中創(chuàng)建了一個(gè)path.properties文件,里面用來存放我即將使用的路徑,以名字=值的方式存放。例如:
realPath = D:/file/
7.3 解析自己的.properties文件:
public class PropertiesUtil {
 private static PropertiesUtil manager = null;
 private static Object managerLock = new Object();
 private Object propertiesLock = new Object();
 private static String DATABASE_CONFIG_FILE = "/path.properties";
 private Properties properties = null;
 public static PropertiesUtil getInstance() {
  if (manager == null) {
   synchronized (managerLock) {
    if (manager == null) {
     manager = new PropertiesUtil();
    }
   }
  }
  return manager;
 }
 private PropertiesUtil() {
 }
 public static String getProperty(String name) {
  return getInstance()._getProperty(name);
 }
 private String _getProperty(String name) {
  initProperty();
  String property = properties.getProperty(name);
  if (property == null) {
   return "";
  } else {
   return property.trim();
  }
 }
 public static Enumeration<?> propertyNames() {
  return getInstance()._propertyNames();
 }
 private Enumeration<?> _propertyNames() {
  initProperty();
  return properties.propertyNames();
 }
 private void initProperty() {
  if (properties == null) {
   synchronized (propertiesLock) {
    if (properties == null) {
     loadProperties();
    }
   }
  }
 }
 private void loadProperties() {
  properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(DATABASE_CONFIG_FILE);
   properties.load(in);
  } catch (Exception e) {
   System.err
     .println("Error reading conf properties in PropertiesUtil.loadProps() "
       + e);
   e.printStackTrace();
  } finally {
   try {
    in.close();
   } catch (Exception e) {
   }
  }
 }
 /**
  * 提供配置文件路徑
  * 
  * @param filePath
  * @return
  */
 public Properties loadProperties(String filePath) {
  Properties properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(filePath);
   properties.load(in);
  } catch (Exception e) {
   System.err
     .println("Error reading conf properties in PropertiesUtil.loadProperties() "
       + e);
   e.printStackTrace();
  } finally {
   try {
    in.close();
   } catch (Exception e) {
   }
  }
  return properties;
 }
}
當(dāng)我們使用之前,我們只需要給 DATABASE_CONFIG_FILE 屬性附上值,就是我們.properties文件的名稱,當(dāng)使用的時(shí)候,我們就可以直接使用類名. getProperty(“realPath”);的方式就可以獲取到在.properties文件中的key為realPath的內(nèi)容。
以上所述是小編給大家介紹的Java開發(fā)中讀取XML與properties配置文件的方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時(shí)回復(fù)大家的!
相關(guān)文章
 關(guān)于Hibernate的一些學(xué)習(xí)心得總結(jié)
Hibernate是一個(gè)優(yōu)秀的Java 持久化層解決方案,是當(dāng)今主流的對象—關(guān)系映射(ORM)工具2013-07-07
 Java中Easypoi實(shí)現(xiàn)excel多sheet表導(dǎo)入導(dǎo)出功能
這篇文章主要介紹了Java中Easypoi實(shí)現(xiàn)excel多sheet表導(dǎo)入導(dǎo)出功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
 spring boot使用自定義的線程池執(zhí)行Async任務(wù)
這篇文章主要介紹了spring boot使用自定義的線程池執(zhí)行Async任務(wù)的相關(guān)資料,需要的朋友可以參考下2018-02-02
 Spring Boot + Jpa(Hibernate) 架構(gòu)基本配置詳解
本篇文章主要介紹了Spring Boot + Jpa(Hibernate) 架構(gòu)基本配置詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
 推薦兩款java開發(fā)實(shí)用工具 hutool 和 lombok
通過本文給大家推薦兩款java開發(fā)實(shí)用工具 hutool 和 lombok,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-04-04
 FileUtils擴(kuò)展readURLtoString讀取url內(nèi)容
這篇文章主要介紹了FileUtils擴(kuò)展readURLtoString使用其支持讀取URL內(nèi)容為String,支持帶POST傳大量參數(shù),大家參考使用吧2014-01-01
 Spring Cloud實(shí)戰(zhàn)技巧之使用隨機(jī)端口
這篇文章主要給大家介紹了關(guān)于Spring Cloud實(shí)戰(zhàn)技巧之使用隨機(jī)端口的相關(guān)資料,文中介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。2017-06-06
 基于自定義BufferedReader中的read和readLine方法
下面小編就為大家分享一篇基于自定義BufferedReader中的read和readLine方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12

