Properties類

前言:

         在部署程序時總會有些變量需要隨着環境的變化或者其它原因,需要進行修改。如果這些參數是直接寫死在程序中,那麼我們每次修改都需要重新編譯,不是很方便。

      有兩種解決方法: 1、使用spring注入的方式,將參數值傳入;2:、寫入文件中進行解析。

 對於方法1,如果多個bean需要傳參,逐一查找不方便,可以使用佔位符,將參數和對應值統一寫到一個文件中,編譯的時候進行替換,最終的內部機制和方法2一樣。

      使用Properties類可以對配置文件進行解析,將其以key/value對的形式,進行set 和get。

一:Properties類介紹

      Properties類是Hashtable<Object,Object>的子類,有getProperty()  load()  store()  setProperty()  clear()方法

其中: public String getProperty(String key)   傳入一個key值返回對應的value值;

            load(InputStream inStream)   加載文本的輸入流,解析裏面以 xxx=yyy存儲的信息

            public synchronized Object setProperty(String key, String value)  設置 k / v 對
            public void store(OutputStream out, String comments)  將hashtable存儲的k/v對信息,輸出到輸出流,參數comments是自定義的註釋信息

           clear() 清空hashtable

二: 簡單實例

package com.netboy.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 讀取配置文件search.properties的demo程序
 * 
 */
public class SimpleMain {
	public static void main(String[] args) throws IOException {
		String filePath = "./conf/search.properties";

		FileInputStream fileStream = new FileInputStream(filePath);
		FileOutputStream outputStream = new FileOutputStream("./conf/store.properties");
		Properties properties = new Properties();
		properties.load(fileStream);
		System.out.println("the daily.ip is :" + properties.getProperty("daily.ip"));
		System.out.println("the local.ip is :" + properties.getProperty("local.ip"));
		System.out.println("the online.ip is :" + properties.getProperty("online.ip"));
		System.out.println("the jetty.port is :" + properties.getProperty("jetty.port"));
		properties.setProperty("netboy", "search demo");
		properties.store(outputStream,"test");
		properties.clear();
		System.out.println("Hello World!");
	}
}

search.properties內容如下:

daily.ip=192.168.1.1
local.ip=127.0.0.1
online.ip=222.222.222.222
!jetty.port=8989
#jetty.port=8989

注意:由源碼可以看出,使用! 和# 都可以起到註釋的作用,properties.java 源碼片段:

		if (isNewLine) {
		    isNewLine = false;
		    if (c == '#' || c == '!') {
			isCommentLine = true;
			continue;
		    }
		}

工程框架:



三:這裏只是簡單介紹下,使用佔位符進行自動替換打包,可以參考我之前的文章:   簡單 maven工程 spring注入 自動打包


發佈了41 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章