转自
http://blog.csdn.net/nineday/article/details/1683437
有时候有些常量需要根据需要作改动,如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)读取的代码如下:










































(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才能生效。