一个读取属性文件的类

在编写服务器端代码的时候,常常需要设置一些服务器的属性入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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值