有時候有些常量需要根據需要作改動,如IP,port,數據庫的鏈接URL等,一般情況下我們把這些常量放在後綴是.properties的文件裏,這樣既可以修改也很方便讀取。下面是以jboss作服務器作的一個讀取.properties的實驗,很簡單。
ResourceBundle的getBundle("filename")方法會默認地到jboss的/server/conf/目錄下找filename.properties文件,然後再調用ResourceBundle實例的getString("key"),通過關鍵字取得值。我曾經在純jdk環境下作過同樣的實驗,默認會到.java的輸出目錄(按照習慣是bin/目錄)下找filename.properties文件。
在Jboss的實驗步驟如下:
(1)在jboss的/server/conf/ 下建一個屬性文件--config.properties,其內容如下:
socket.ip=192.168.0.1
socket.port=60000
socket.timeout=10000
(2)讀取的代碼如下:
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* create on 20070709
* @author nineday
*
* to get property from file .properties
*/
public final class Config{
private static ResourceBundle configResource = null;
/**
* initialization
*/
public static void initConfig(){
try{
configResource = ResourceBundle.getBundle("config");//file name
}catch(MissingResourceException mre){
mre.printStackTrace();
}
}
/**
*get value
*@param String key
*@return String value
*/
public static String getValue(String key){
if (configResource == null) initConfig();
try{
return new String(
(configResource.getString(key))
.getBytes("ISO8859_1"),"gb2312");
}catch(Exception e){
return null;
}
}
}
(3)調用的代碼:
import nineday.common.Config;
import java.net.Socket;
/**
* to provide socket service
*
* @author nineday
*
*/
public class SocketService {
//private static final Log log = LogFactory.getLog(SocketService.class);
private static final String socketServerIP = Config.getValue("socket.ip");
private static final int socketServerPort = Integer.parseInt(Config.getValue("socket.port"));
private static final int socketTimeout = Integer.parseInt(Config.getValue("socket.timeout"));
public static Socket getSocketInstance()throws Exception{
//log.debug("start a new socket to "+socketServerIP+":"+socketServerPort);
Socket socketServer = null;
socketServer=new Socket(socketServerIP,socketServerPort);
socketServer.setSoTimeout(socketTimeout);
return socketServer;
}
}
注意:
(1)如果文件的路徑是/server/conf/folder , 載入文件的代碼這樣寫ResourceBundle.getBundle("folder.filename"); ‘.’代表的是文件的下一層,所以文件名一定不能包含‘.’。
(2)jboss在啓動的時候加載屬性文件到內存,所以當我們修改屬性文件,必須重啓jboss才能生效。