在编写服务器端代码的时候,常常需要设置一些服务器的属性入Host,Port,databaseUrl等等,往往写在后缀为properties 的属性文件中,下面是一个读取属性文件属性和值的类。
Properties.java
==========================================
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.io.InputStream;
import java.io.BufferedReader;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
*
* 由于java.util.Properties 对应的是ISO 8859-1编码方式。
* 所以其他编码的属性文件需要自行处理。
* 基本功能:
* 以“#”,“!”开头的行被当做注释。
* 属性项与值的格式为:key=value
* 值的前后引号在这里被删除。
*
*/
public class Properties {
public static final Pattern pComment= Pattern.compile("^[#!].*$");
public static final Pattern pKeyVal= Pattern.compile("^([//.//w]+)//s*=//s*(.*)$");
public static final Pattern pQuote= Pattern.compile("^/"(.*)/"$");
public staticStringencodeType= "ISO 8859-1";
public final HashMapkeyval= new HashMap();
public void load(String name) throws IOException {
InputStream inStream= Properties.class.getResourceAsStream(name);
InputStreamReader inReader= new InputStreamReader(inStream, encodeType);
BufferedReaderin= new BufferedReader(inReader);
String line= null;
while((line = in.readLine()) != null) {
line= line.trim();
if (line.length() == 0) {
continue;
}
// comment line
Matcher m= pComment.matcher(line);
if (m.matches()) {
continue;
}
// key=value
m= pKeyVal.matcher(line);
if (!m.matches()) {
continue;
}
String key = new String(m.group(1));
String val = new String(m.group(2));
m= pQuote.matcher(val);
if (m.matches()) {
val= new String(m.group(1));
}
keyval.put(key, val);
}
}
public Properties(String fileName,String _encodeType) throws FileNotFoundException, IOException
{
load(fileName);
if( _encodeType != null) {
this.encodeType = _encodeType ;
}
}
public String getStrValue(String key) throws UnsupportedEncodingException {
String val= null;
Object o = keyval.get(key);
if (o instanceof String) {
val= (String)o;
}
return val;
}
public int getIntValue(String key) throws UnsupportedEncodingException {
int val= 0;
try {
Object o = keyval.get(key);
if (o instanceof String) {
val= Integer.parseInt((String)o);
}
}
catch (Exception e) {
}
return val;
}
}