標籤:記錄 常用 協助 建立 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設定檔