ssslinppp

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
主要介绍了:
  • 消息格式化的基本使用;
  • 格式化:匹配数字;
  • 格式化:匹配日期;
  • 格式化:匹配时间;
  • 格式化:多次匹配;

MessageFormat用来格式化一个消息,通常是一个字符串。MessageFormat模式的主要部分:

下面是详细配置:


示例程序
  1. package com.sssppp.Format;
  2. import java.text.MessageFormat;
  3. import java.util.Arrays;
  4. import java.util.Date;
  5. import java.util.List;
  6. public class MessageFormatExample {
  7. public static void main(String[] args) {
  8. // 基本匹配
  9. String message = "基本匹配:{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}";
  10. Object[] array = new Object[] { "A", "B", "C", "D", "E", "F", "G", "H",
  11. "I", "J", "K", "L", "M", "N", "O", "P", "Q" };
  12. String value = MessageFormat.format(message, array);
  13. System.out.println(value); // ABCDEFGHIJKLMNOPQ
  14. String message1 = "基本匹配:{0} is a person";
  15. Object[] array1 = new Object[] { "ZhangSan" };
  16. String value1 = MessageFormat.format(message1, array1);
  17. System.out.println(value1); // oh, ZhangSan is a person
  18. System.out.println();
  19. // 数字匹配
  20. System.out.println("数字匹配,匹配:3.1415");
  21. List<String> numList = Arrays.asList("integer", "currency", "percent",
  22. "#.##", "00.##");
  23. for (String string : numList) {
  24. String message2 = "{0,number," + string + "}";
  25. Object[] array2 = new Object[] { new Double(3.1415) };
  26. String value2 = MessageFormat.format(message2, array2);
  27. System.out.println(value2);
  28. }
  29. System.out.println();
  30. // 日期匹配
  31. System.out.println("日期匹配");
  32. List<String> dateList = Arrays.asList("yyyyMMdd-HH:mm:ss", "short",
  33. "medium", "long", "full");
  34. for (String string : dateList) {
  35. String message3 = "{0,date," + string + "}";
  36. String value3 = MessageFormat.format(message3, new Date());
  37. System.out.println(value3);
  38. }
  39. System.out.println();
  40. // 时间匹配
  41. System.out.println("时间匹配");
  42. List<String> timeList = Arrays.asList("yyyyMMdd-HH:mm:ss", "short",
  43. "medium", "long", "full");
  44. for (String string : timeList) {
  45. String message4 = "{0,time," + string + "}";
  46. String value4 = MessageFormat.format(message4, new Date());
  47. System.out.println(value4);
  48. }
  49. System.out.println();
  50. // 多次匹配
  51. String message8 = "多次匹配:{0} | {1} | {0} | {1}";
  52. Object[] array8 = new Object[] { "A", "B" };
  53. String value8 = MessageFormat.format(message8, array8);
  54. System.out.println(value8); // A | B | A | B
  55. }
  56. }

运行结果
  1. 基本匹配:ABCDEFGHIJKLMNOPQ
  2. 基本匹配:ZhangSan is a person
  3. 数字匹配,匹配:3.1415
  4. 3
  5. 3.14
  6. 314%
  7. 3.14
  8. 03.14
  9. 日期匹配
  10. 20161201-17:13:05
  11. 16-12-1
  12. 2016-12-1
  13. 2016121
  14. 2016121 星期四
  15. 时间匹配
  16. 20161201-17:13:05
  17. 下午5:13
  18. 17:13:05
  19. 下午051305
  20. 下午051305 CST
  21. 多次匹配:A | B | A | B






posted on 2016-12-01 17:19  ssslinppp  阅读(4582)  评论(0编辑  收藏  举报