读配置文件,传参数,打印message


     为了将来维护,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 不存在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值