信息的格式转换
基类java.text.Format
日期(DateFormat)
数字(NunmberFormat)
消息(MessageFormat)
※ Format非线程安全,每个线程最好独立创建,可以搭配TheadLocal
Format最直观的用法是对象和字符串的相互转换
当然也可以提供位置信息等进行细粒度操作,由子类负责具体实现
内部采用StringBuffer
实现
Format.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public abstract class Format implements Serializable , Cloneable { public final String format (Object obj) { return format(obj, new StringBuffer(), new FieldPosition(0 )).toString(); } public abstract StringBuffer format (Object obj, StringBuffer toAppendTo, FieldPosition pos) ; public Object parseObject (String source) throws ParseException { ParsePosition pos = new ParsePosition(0 ); Object result = parseObject(source, pos); if (pos.index == 0 ) { throw new ParseException("Format.parseObject(String) failed" , pos.errorIndex); } return result; } public abstract Object parseObject (String source, ParsePosition pos) ; }
1 2 3 Format |---DateFormat |---SimpleDateFormat
DateFormat使用工厂方法获取实例,并且可配置style和locale
getTimeInstance
getDateInstance
getDateTimeInstance
DateFormat.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public static final int FULL = 0 ;public static final int LONG = 1 ;public static final int MEDIUM = 2 ;public static final int SHORT = 3 ;public static final int DEFAULT = MEDIUM;public final static DateFormat getInstance () { return getDateTimeInstance(SHORT, SHORT); } public final static DateFormat getDateTimeInstance () { return get(DEFAULT, DEFAULT, 3 , Locale.getDefault()); } public final static DateFormat getDateTimeInstance (int dateStyle, int timeStyle) { return get(timeStyle, dateStyle, 3 , Locale.getDefault()); }
默认格式
Sample 1 2 3 4 5 Date d = new Date(); System.out.println(DateFormat.getInstance().format(d)); System.out.println(DateFormat.getDateTimeInstance().format(d)); System.out.println(DateFormat.getDateInstance().format(d)); System.out.println(DateFormat.getTimeInstance().format(d));
1 2 3 Format |---NumberFormat |---ChoiceFormat
根据数字范围来决定相应的字符串,注意超出最低边界会沿用范围结果
直接表达式构造
Sample 1 2 3 4 5 ChoiceFormat cf = new ChoiceFormat("-1#negative|0#zero|0<positive" ); System.out.println(cf.format(1 )); System.out.println(cf.format(0 )); System.out.println(cf.format(-0.5 )); System.out.println(cf.format(-1.5 ));
也可以拆分构造
Sample 1 2 3 4 5 6 7 double [] limits = { -1 , 0 , 1 };String[] formats = { "negative" , "zero" , "positive" }; ChoiceFormat cf = new ChoiceFormat(limits, formats); System.out.println(cf.format(1 )); System.out.println(cf.format(0 )); System.out.println(cf.format(-0.5 )); System.out.println(cf.format(-1.5 ));
1 2 Format |--- MessageFormat
实现简单的占位替换
Sample 1 2 MessageFormat.format("first:{0} second:{1}" , "foo" , "bar" );
除了指定位置索引,还可以指定一些类型
Sample 1 2 MessageFormat.format("date:{0,date} time:{0,time} progress:{1,number,percent}" , new Date(), 0.8 );