java讀取設定檔一些方法總結

來源:互聯網
上載者:User

Jakarta Commons的configuration包讀取設定檔

設定檔一般常見的有兩種:索引值對格式,或XML設定檔,讀取這類設定檔可以用Commons Configuration包。

索引值對格式也就是常見的.properties檔案。通過PropertiesConfiguration讀取,如下:

 代碼如下 複製代碼

package com.guoweiwei.test.configuration;
import java.util.List;
import org.apache.commons.configuration.Configuration;

import org.apache.commons.configuration.ConfigurationException;

import org.apache.commons.configuration.PropertiesConfiguration;

public class PropertiesReadExample {

    /**

     * @param args

     * @throws ConfigurationException

     */

    public static void main(String[] args) throws ConfigurationException {

       Configuration config = new PropertiesConfiguration(“com/guoweiwei/test/configuration/test.properties”);

       float speed = config.getFloat(“speed”);

       List names = config.getList(“names”);

       boolean correct = config.getBoolean(“correct”);

       System.out.println(“speed:” + speed);

       System.out.println(“names:” + names.size());

       System.out.println(“correct:” + correct);

    }

}

當然對XML檔案的讀取和解析也是如此簡單:

 代碼如下 複製代碼

package com.guoweiwei.test.configuration;import java.util.List;

import org.apache.commons.configuration.Configuration;

import org.apache.commons.configuration.ConfigurationException;

import org.apache.commons.configuration.XMLConfiguration;

public class XMLReadExample {

    private static final String RESOURCE_FILE = “com/guoweiwei/test/configuration/test.xml”;

    /**

     * @param args

     * @throws ConfigurationException

     */

    public static void main(String[] args) throws ConfigurationException {

       Configuration config = new XMLConfiguration(RESOURCE_FILE);

       List startCriteria = config.getList(“start-criteria.criteria”);

       String firstCriteria = config.getString(“start-criteria.criteria(0)”);

       String firstCriteriaType = config.getString(“start-criteria.criteria(0)[@type]“);

       int horsepower = config.getInt(“horsepower”);

       System.out.println(“startCriteria:” + startCriteria.size());

       System.out.println(“firstCriteria:” + firstCriteria);

       System.out.println(“firstCriteriaType:” + firstCriteriaType);

       System.out.println(“horsepower:” + horsepower);

    }

}

從上面的代碼可以看出,XMLConfiguration的getXXX()方法還支援XPath解析XML檔案。

此外,可以綜合使用XML和屬性檔案讀取設定檔,比如一種常見的情境:

應用程式的配置有多個不同的地方。首先是一個全域配置;然後某個地方可能需要局部配置,當兩者重複時以局部配置為準,然後還有一個使用者自訂的設定檔,使用者自訂的設定檔優先順序又高於局部配置和全域配置。這個時候就可以考慮用一個ConfigurationFactory來管理了,將三個不同的設定檔分別定義為global.properties、local.properties、user.properties,然後通過一個configuration.xml的檔案來管理三者之間的優先順序關係,如下所示:

屬性設定檔之一global.properties

threads.max=50threas.min=2

timout=15.52

interactive=true

color=red

speed=50

name=Default User
 

屬性設定檔之二local.properties

threads.max=30speed=55

屬性設定檔之三user.properties

threads.min=1color=black

speed=5000

name=Sean
 

管理這三個屬性設定檔的設定檔configuration.xml

 代碼如下 複製代碼

<?xml version=“1.0″ encoding=“UTF-8″?><configuration>

    <properties fileName=“user.properties”/>

    <properties fileName=“local.properties”/>

    <properties fileName=“global.properties”/>

</configuration>
 

然後,應用程式中可以這樣使用:

 代碼如下 複製代碼

package com.guoweiwei.test.configuration;import java.net.MalformedURLException;

import java.net.URL;

import org.apache.commons.configuration.Configuration;

import org.apache.commons.configuration.ConfigurationException;

import org.apache.commons.configuration.ConfigurationFactory;

public class ComplexConfigExample {

    private static final String RESOURCE_FILE = “com/guoweiwei/test/configuration/complex/configuration.xml”;

    /**

     * @param args

     * @throws ConfigurationException

     * @throws MalformedURLException

     */

    public static void main(String[] args) throws ConfigurationException, MalformedURLException {

       ComplexConfigExample c = new ComplexConfigExample();

       c.ReadComplexConfiguration();

    }

    private void ReadComplexConfiguration() throws ConfigurationException{

       ConfigurationFactory factory = new ConfigurationFactory();

       //URL url = this.getClass().getResource(RESOURCE_FILE);

       URL url = this.getClass().getResource(“complex/configuration.xml”);

       factory.setConfigurationURL(url);

       Configuration config = factory.getConfiguration();

       System.out.println(“Timeout:”+config.getFloat(“timout”));

       System.out.println(“Max Thread:”+config.getInt(“threads.max”));

       System.out.println(“Name:”+config.getString(“name”));

       System.out.println(“Speed:”+config.getInt(“speed”));

    }

}

最後的輸出結果如下:

Timeout:15.52 【來自於global.properties】Max Thread:30 【來自於local.properties】

Name:Sean 【來自於user.properties】

Speed:5000 【來自於user.properties】
 

spring讀取設定檔


一.讀取xml設定檔

    (一)建立一個java bean(HelloBean.java)
    java 代碼

  

 代碼如下 複製代碼
      package chb.demo.vo;  
         
        public class HelloBean {  
         private String helloWorld;  
         
         public String getHelloWorld() {  
          return helloWorld;  
         }  
         
         public void setHelloWorld(String helloWorld) {  
          this.helloWorld = helloWorld;  
         }  
        }  
         

    (二)構造一個設定檔(beanConfig.xml)
    xml 代碼

    

 代碼如下 複製代碼

    <!---->xml version="1.0" encoding="UTF-8"?> 
        <!---->> 
        <beans> 
         <bean id="helloBean" class="chb.demo.vo.HelloBean"> 
          <property name="helloWorld"> 
           <value>Hello!chb!value> 
          property> 
         bean> 
        beans> 

   

(三)讀取xml檔案
    1.利用ClassPathXmlApplicationContext
    java 代碼

 

 代碼如下 複製代碼
       ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");  
        HelloBean helloBean = (HelloBean)context.getBean("helloBean");  
        System.out.println(helloBean.getHelloWorld()); 

    2.利用FileSystemResource讀取
    java 代碼

    

 代碼如下 複製代碼
    Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");  
          BeanFactory factory = new XmlBeanFactory(rs);  
          HelloBean helloBean = (HelloBean)factory.getBean("helloBean");  
          System.out.println(helloBean.getHelloWorld());  

     值得注意的是:利用FileSystemResource,則設定檔必須放在project直接目錄下,或者寫明絕對路徑,否則就會拋出找不到檔案的異常

二.讀取properties設定檔

    這裡介紹兩種技術:利用spring讀取properties 檔案和利用java.util.Properties讀取
    (一)利用spring讀取properties 檔案
    我們還利用上面的HelloBean.java檔案,構造如下beanConfig.properties檔案:
    properties 代碼

 代碼如下 複製代碼

        helloBean.class=chb.demo.vo.HelloBean  
        helloBean.helloWorld=Hello!chb! 

    屬性檔案中的"helloBean"名稱即是Bean的別名設定,.class用於指定類來源。
    然後利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader來讀取屬性檔案
    java 代碼

      

 代碼如下 複製代碼
  BeanDefinitionRegistry reg = new DefaultListableBeanFactory();  
         PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);  
         reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));  
         BeanFactory factory = (BeanFactory)reg;  
         HelloBean helloBean = (HelloBean)factory.getBean("helloBean");  
         System.out.println(helloBean.getHelloWorld());  

     
    (二)利用java.util.Properties讀取屬性檔案
    比如,我們構造一個ipConfig.properties來儲存伺服器ip地址和連接埠,如:
    properties 代碼

        ip=192.168.0.1  
        port=8080 

    則,我們可以用如下程式來獲得伺服器配置資訊:
    java 代碼

     

 代碼如下 複製代碼
   InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");  
          Properties p = new Properties();  
          try {  
           p.load(inputStream);  
          } catch (IOException e1) {  
           e1.printStackTrace();  
          }  
        System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port")); 

本文只介紹了一些簡單操作,不當之處希望大家多多指教

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.