JAVA讀取PROPERTIES設定檔

來源:互聯網
上載者:User

標籤:記錄   常用   協助   建立   inpu   java讀取   引號   php   extc   

項目經常用到json,xml,properties,文字檔等,作為設定檔。用來儲存連接字串或其他配置參數等。

本文記錄properties。

properties檔案,儲存格式 鍵=值。例如建立一個 config.properties檔案:

12345678 ####這裡是config.properties檔案,儲存資料庫資訊#####資料庫ipconnip=192.168.10.29username=      user1password=pwd1#username=    user2#password=test2user="user1"
properties檔案特點:

1,索引值對格式

2,=等號後面,值前面,的空格,會自動忽略掉

3,值後面的空格,不會忽略

4,=等號後面的雙引號,不會忽略

5,#井號後面內容,為注釋,忽略

所以,讀取config.properties,通過key擷取值,得到結果為:

connip為[192.168.10.29]

username為[user1]

password為[pwd1 ? ?] ? 這裡要注意,pwd1後面有空格

user為[“user1”] 這裡要注意,值,包括雙引號。

 

在java中操作properties的類為,java.util.Properties。

讀取properties的方法,比較簡單

三步:

1,載入資源; 2,通過key擷取值; 3,測試輸出

1234567891011 public static void main(String[] args) throws IOException {    Properties properties = new Properties();    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");    properties.load(inputStream);     String result1 = properties.getProperty("connip");    String result2 = properties.getProperty("sdfds", "error");     System.err.println(result1);    System.err.println(result2);}

輸出結果為:

192.168.10.29

error

 

程式說明:

1、資源載入

Thread.currentThread().getContextClassLoader().getResourceAsStream(“config.properties”);

這裡用到了這個格式資源載入方式。

 

2、properties注意getProperty,有一個重載。

一個是直接擷取值

另一個是當key不存在時,返回預設值

(完)

 

關於資源載入:
1234567891011 public class PropertiesTest {    public static void main(String[] args) throws IOException {        String path1 = Thread.currentThread().getContextClassLoader().getResource(".").getPath();        String path2 = PropertiesTest.class.getClassLoader().getResource(".").getPath();        String path3 = PropertiesTest.class.getResource(".").getPath();         System.err.println("path1:" + path1);        System.err.println("path2:" + path2);        System.err.println("path3:" + path3);    }}

輸出:

path1:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/

path2:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/

path3:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/my/properties/

 

亂碼

讀取properties的協助類:

 

轉自部落格:http://www.weixuehao.com/archives/357

JAVA讀取PROPERTIES設定檔

聯繫我們

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