为了将来维护,message内容可能需要更改,这样就不能将message写死在程序中,一种做法是将message放在一个配置文件中,然后在程序中通过messageID,打印各种信息。
message内容如下(msg.properties):
JOC0033E={0}不满足日期格式(YYYYMMDD)。
JBC0037E=当前处理对象为对象外。通番 = {0} 日期 = {1} 表A通番 = {2}
JOC0025E=密码输入错误。
其中{}内都是参数,需要在程序中传递
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Test.errorMsgOutput("145201F","hello","world"," 111 "," 222","333");
Test.errorMsgOutput("JOC0033E", "2012/01111");
Test.errorMsgOutput("JBC0037E", "10101"," 20120313","01");
Test.errorMsgOutput("xxxxxxx");
}
/**
* 输出指定msgID的内容,如果msg没有参数,第二个参数可以不给出
* @param msgId msgID
* @param msgPara msg参数
*/
public static void errorMsgOutput(String msgId, String... msgPara) {
String msgStruct = getMsgStruts(msgId);
if (msgStruct==null) {
System.out.println("信息ID:"+msgId+" 不存在");
return;
}
Pattern pattern = Pattern.compile("\\{\\d\\}");
Matcher matcher = pattern.matcher(msgStruct);
int i = 0;
int count = 0;
while (matcher.find()) {
if (msgPara.length == 0) {
System.out.println("信息参数未给出");
return;
}
String temp = msgStruct.replace(matcher.group(0), msgPara[i]);
msgStruct = temp;
if (i < msgPara.length - 1) {
i++;
}
count++;
}
if (count != msgPara.length) {
System.out.println("信息参数个数不正");
} else {
System.out.println(msgStruct);
}
}
/**
* 根据MSGID获取对应的信息内容结构
* @param msgId msgID
* @return msg内容结构
*/
public static String getMsgStruts(String msgId) {
String s = "";
Properties p = new Properties();// 加载属性文件读取类
InputStreamReader inputStream = null;
try {
InputStream i = new FileInputStream("msg.properties");
inputStream = new InputStreamReader(i, "utf-8");
p.load(inputStream);// 属性文件将该流加入的可被读取的属性中
i.close();
inputStream.close();// 读完了关闭
s = p.getProperty(msgId);// 取得对应的属性值
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
输出如下:
信息ID:145201F 不存在
2012/01111不满足日期格式(YYYYMMDD)。
当前处理对象为对象外。通番 = 10101 日期 = 20120313 表A通番 = 01
信息ID:xxxxxxx 不存在