消息格式化
用户登录成功后一般会有这种信息“xxx,下午好”,这时显示了用户名,那么此时如果这些内容保存在了资源文件里面,则就需要通过占位符来进行描述,同时对于读取出来的数据也许呀进行消息格式化处理。
范例:修改资源文件
【中文资源文件】message.Messages_zh_CN.properties | info = 欢迎{0}的访问,当期日期是{1}! |
【英文资源文件】message.Messages_en_US.properties | info = Welcome{0},date:{1}! |
如果有需要则可以继续添加“{1},{2}”之类的内容。
此时如果要进行资源读取则会将占位符的信息一起读取出来,所以此时就需要利用MessageFormat类进行格式化处理。
MessageFormat提供的格式化文本的方法:public static String format(String pattern, Object... arguments)
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.SimpleFormatter;
public class ResourceBundlel类 {
public static void main(String[] args) {
Locale locale1 = new Locale("en","US");
//获取实例化对象,第一个选项填资源的基础名(除去语言代码后的共同名字),第二个填获取的区域
ResourceBundle resourceBundle = ResourceBundle.getBundle("message.Messages",locale1);
String val = resourceBundle.getString("info"); //读取对应的info key资源内容
System.out.println(MessageFormat.format(val, " US User",new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
}
}
Welcome US User,Date:2021-01-13