properties設定檔讀取操作總結【java筆記】

來源:互聯網
上載者:User

標籤:sdn   soft   output   net   擴充   sys   exce   使用   system   

聲明:本文所有例子中的 properties 檔案均放在 src 目錄下,ecclipse 軟體自動增加

一、基本概念

  1.1 

    properties檔案,儲存格式 鍵=值。

    properties檔案特點:

      1、索引值對格式
      2、“ = ”等號後面,值前面,的空格,會自動忽略掉
      3、值後面的空格,不會忽略
      4、“ = ”等號後面的雙引號,不會忽略
      5、“ # ”井號後面內容,為注釋,忽略

  1.2 Java的 Properties 類 屬性對應(property map)

  是一種儲存鍵/值對的資料結構。屬性對應經常被用來存放配置資訊。

  它有三個特性:

    1. 鍵和值鬥志字串

    2. 鍵/值對可以很容易地寫入檔案或從檔案讀出

    3. 用二級表存放預設值

  實現屬性對應的Java類被稱為 Properties(Java.util.Properties),此類是Java中比較重要的類,

  主要用於讀取Java的設定檔,各種語言都有自己所支援的設定檔,設定檔中很多變數是經常改變的,

  這樣做也是為了方便使用者,讓使用者能夠脫離程式本身去修改相關的變數設定,提高程式的可擴充性。

  此類是安全執行緒的:多個線程可以共用單個 Properties 對象而無需進行外部同步。

  構造方法:

    • Properties() 建立一個無預設值的空屬性列表。
    • Properties( Properties defaults ) 建立一個帶有指定預設值的空屬性列表。

  它提供了幾個主要的方法:
    getProperty ( String key):用指定的鍵在此屬性列表中搜尋屬性。也就是通過參數 key ,得到 key 所對應的 value。

    load ( InputStream inStream):從輸入資料流中讀取屬性列表(鍵和元素對)。通過對指定的檔案(比如說上面的 test.properties 檔案)進行裝載來擷取該檔案中的所有鍵 - 值對。以供 getProperty ( String key) 來搜尋。

    setProperty ( String key, String value) :底層調用 Hashtable 的方法 put 。他通過調用基類的put方法來設定 鍵 - 值對。

    store ( OutputStream out, String comments):以適合使用 load 方法載入到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出資料流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的檔案中去。

    clear ():清除所有裝載的 鍵 - 值對。該方法在基類中提供。

    注意:因為 Properties 繼承於 Hashtable,所以可對 Properties 對象應用 put 和 putAll 方法。但不建議使用這兩個方法,因為它們允許調用者插入其鍵或值不是 String 的項。相反,應該使用 setProperty 方法。

    如果在“不安全”的 Properties 對象(即包含非 String 的鍵或值)上調用 store 或 save 方法,則該調用將失敗。

    類似地,如果在“不安全”的 Properties 對象(即包含非 String 的鍵)上調用 propertyNames 或 list 方法,則該調用將失敗。

二、Java讀取Properties檔案的方法

  2.1 Java虛擬機器(JVM)有自己的系統設定檔(system.properties)

//擷取JVM的系統屬性  import java.util.Properties;  public class ReadJVM {      public static void main(String[] args) {          Properties pps = System.getProperties();          pps.list(System.out);      }  }  

 

  2.2 使用 J2SE API 讀取 Properties 檔案的六種方法

  方法一:java.util.Properties類的 load() 方法

    InputStream in = new BufferedInputStream(new FileInputStream(name));
    Properties p = new Properties();
    p.load(in);

  /**     * 注意:設定檔一定要放到項目的根目錄。     */    @Test    public void run1() {        try {            FileInputStream is = new FileInputStream("src/my-ini.properties");            Properties pop = new Properties();            try {                pop.load(is);            } catch (IOException e) {                e.printStackTrace();            }            Enumeration em = pop.propertyNames();            while(em.hasMoreElements()) {                String key = (String) em.nextElement();                String value = pop.getProperty(key);                System.out.println(key+"="+value);            }                    } catch (FileNotFoundException e) {            e.printStackTrace();        }    }

  方法二:使用class變數的getResourceAsStream()方法

    InputStream in = JProperties.class.getResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

    /**     * 注意:設定檔一定要放到目前的目錄下。     * (目錄層次也可以從src下面的檔案夾開始但不必包含src,且不必包含反斜線開頭。)      * 本方法在 PropertiesDemo1 類中     */    @Test    public void run2() {        Properties pop = new Properties();        try{            InputStream in = PropertiesDemo1.class.getResourceAsStream("/my-ini.properties");            pop.load(in);        }catch(Exception ex) {            ex.printStackTrace();        }        Enumeration em = pop.propertyNames();        while(em.hasMoreElements()) {            String key = (String) em.nextElement();            String value = pop.getProperty(key);            System.out.println(key+"="+value);        }                    }

  方法三:使用 class.getClassLoader() 所得到的 java.lang.ClassLoader 的 getResourceAsStream() 方法

    InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

  /**     * 注意:     * 設定檔一定要放在 bin 目錄下
   * 注意 eclipse 軟體自動將src中的設定檔複製到 bin 目錄下
*/ @Test public void run3() { Properties pop = new Properties(); try{ InputStream in = PropertiesDemo1.class.getClassLoader().getResourceAsStream("my-ini.properties"); pop.load(in); }catch(Exception ex) { ex.printStackTrace(); } Enumeration em = pop.propertyNames(); while(em.hasMoreElements()) { String key = (String) em.nextElement(); String value = pop.getProperty(key); System.out.println(key+"="+value); } }

  方法四:使用 java.lang.ClassLoader 類的 getSystemResourceAsStream() 靜態方法

    InputStream in = ClassLoader.getSystemResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

   /**     * 注意:     * 設定檔一定要放在 bin 目錄下     */    @Test    public void run4() {        Properties pop = new Properties();        try{            InputStream in = ClassLoader.getSystemResourceAsStream("my-ini.properties");            pop.load(in);        }catch(Exception ex) {            ex.printStackTrace();        }        Enumeration em = pop.propertyNames();        while(em.hasMoreElements()) {            String key = (String) em.nextElement();            String value = pop.getProperty(key);            System.out.println(key+"="+value);        }    }

  方法五:使用 java.util.ResourceBundle 類的 getBundle() 方法

    ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

  /**     * 注意:     * 設定檔一定要放在 bin 目錄下     */    @Test    public void run5() {        ResourceBundle rs = ResourceBundle.getBundle("my-ini");                String driver = rs.getString("driver");        String url = rs.getString("url");        String user = rs.getString("user");        String password = rs.getString("password");                        System.out.println("driver="+driver);        System.out.println("url="+url);        System.out.println("user="+user);        System.out.println("password="+password);    }

  方法六:使用 java.util.PropertyResourceBundle 類的建構函式

  @Test    public void run6() {        File file = new File("src/my-ini.properties");        try {            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));            try {                PropertyResourceBundle prb = new PropertyResourceBundle(in);                                String driver = prb.getString("driver");                String url = prb.getString("url");                String user = prb.getString("user");                String password = prb.getString("password");                                System.out.println("driver="+driver);                System.out.println("url="+url);                System.out.println("user="+user);                System.out.println("password="+password);            } catch (IOException e) {                e.printStackTrace();            }        } catch (FileNotFoundException e) {            e.printStackTrace();        }    }

 

引用博文: 

JAVA操作properties設定檔——總結(Locale&ResourceBundle& PropertyResourceBundle(http://blog.csdn.net/fanxiaobin577328725/article/details/52071310)

 

properties設定檔讀取操作總結【java筆記】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.