ITeye博客

JAVA中的本地格式(Format):本地消息、本地时间、本地数字

douh · 2010-10-09 18:40 · JAVA Core · 编程语言 · Markdown

JAVA中的本地格式,主要包括本地消息,本地时间,本地数字等。主要在包java.util.text中定义相关接口和类。 Format: 是一个接口,定义了本地化的一些方法,主要包含解析和格式还两种方法。 两个格式化方法:将对象格式化成对应的格式的字符串


format(Object obj) 
format(Object obj, StringBuffer toAppendTo, FieldPosition pos) 

第二个方法中的FieldPosition是用来指明某个Field的位置(Field实际是Format.Field 的子类,而后者又是AttributedCharacterIterator.Attribute的子类。AttributedCharacterIterator.Attribute是实际上就是一个键值对的KEY的名称。 两个解析方法:将特定格式的字符串解析成Object


parseObject(String source) 
parseObject(String source, ParsePosition pos) 

第二个方法中的ParsePosition用来指定开始解析的位置。


formatToCharacterIterator(Object obj) 

这个方法返回格式化字符串的属性字符的迭代器 AttributedCharacterIterator,这个迭代器是CharacterIterator的子类。使用于字符含有特定属性的情况,比如AttributedString。CharacterIterator是字符序列CharSequence的迭代器。

在Format的三个实现类:DateFormat,MessageFormat,NumberFormat,其中 DateFormat和NumberFormat是抽象了类各自都有扩展实现,比较容易理解。MessageFormat比较复杂。

MessageFormat: MessageFormat 提供了一个提供语言相关的(本地化)的消息格式。其原理是在要显示的消息中包含特定的模式,比如,要显示的消息中时间按照长模式进行解析,可以使用{0,time,long}。当参数对象按照模式解析后,替换到模式出现的地方。 MessageFormat 中模式的定义:


MessageFormatPattern:
         String
         MessageFormatPattern FormatElement String

 FormatElement:
         { ArgumentIndex }
         { ArgumentIndex , FormatType }
         { ArgumentIndex , FormatType , FormatStyle }

 FormatType: one of 
         number date time choice

 FormatStyle:
         short
         medium
         long
         full
         integer
         currency
         percent
         SubformatPattern

 String:
         StringPartopt
         String StringPart

 StringPart:
         ''
         ' QuotedString '
         UnquotedString

 SubformatPattern:
         SubformatPatternPartopt
         SubformatPattern SubformatPatternPart

 SubFormatPatternPart:
         ' QuotedPattern '
         UnquotedPattern


在字符串中,"''" 表示单引号。QuotedString 可以包含除单引号之外的任意字符;围绕的单引号被移除,也就是说,最后格式化后,包含的引号没有了。UnquotedString 可以包含除单引号和左花括号之外的任意字符。因此,格式化后消息字符串为 "'{0}'" 的字符串可以写作 "'''{'0}''" 或 "'''{0}'''"。 在 SubformatPattern 中,应用了不同的规则。QuotedPattern 可包含除单引号之外的任意字符,但不移除围绕的单引号,就是说解析父层的模式是,并不处理子模式中的单引号。因此它们可以由子格式解释。例如,"{1,number,$'#',##}" 将产生一个带井号的数字格式,结果如:"$#31,45"。 UnquotedPattern 可以包含除单引号之外的任意字符,但其中的花括号必须成对出现。例如,"ab {0} de" 和 "ab '}' de" 是有效的子格式模式,而 "ab {0'}' de" 和 "ab } de" 则是无效的。

警告: 不过,在消息格式模式中使用引号的规则在一定程度上显示混乱。尤其是,本地化程序并不总是清楚单引号是否需要成对。要确保通知本地化程序关于规则的信息,并告诉它们(例如,通过使用资源包源文件中的注释)MessageFormat 将处理哪些字符串。注意,本地化程序在转换后的字符串中必须使用单引号,其中原始版本不包含单引号。 ArgumentIndex 值是使用数字 '0' 到 '9' 表示的非负整数,它表示传递给 format 方法的 arguments 数组的一个索引,或者表示由 parse 方法返回的结果数组的一个索引。 FormatType 和 FormatStyle 值用来创建格式元素的 Format 实例。SubformatPattern 必须是所使用的 Format 子类的一个有效的模式字符串。 在MessageFormat经常会用到ChoiceFormat 这个类,这个类是NumberFormat的一个子类。这个类提供了在特定数字范围使用格式的功能。范围列表由一个升序double的列表组成,列表中的每个条目,都表示一个半开区间。比如X和标目比较,实际上是: X matches j if and only if limit <= X < limit 代码示例:


package com.al.mj.javatest;

import java.text.ChoiceFormat;
import java.text.Format;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;

public class MessageFormatTest {
	public static void main(String[] args) {
		MessageFormat form = new MessageFormat(
				"The disk \"{1}\" contains ''{0}''.");
		double[] filelimits = { 0, 1, 2 };
		String[] filepart = { "no files", "one file", "{0,number} files" };
		ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
		form.setFormatByArgumentIndex(0, fileform);

		int fileCount = 1333;
		String diskName = "MyDisk";
		Object[] testArgs = { new Long(fileCount), diskName };

		System.out.println(form.format(testArgs));

		double[] limits = { 1, 2, 3, 4, 5, 6, 7 };
		String[] monthNames = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri",
				"Sat" };
		ChoiceFormat cform = new ChoiceFormat(limits, monthNames);
		ParsePosition status = new ParsePosition(0);
		for (double i = 0.0; i <= 8.0; ++i) {
			status.setIndex(0);
			System.out.println(i + " -> " + cform.format(i) + " -> "
					+ cform.parse(cform.format(i), status));
		}

		double[] filelimits2 = { 0, 1, 2 };
		String[] filepart2 = { "are no files", "is one file", "are {2} files" };
		ChoiceFormat fileform2 = new ChoiceFormat(filelimits2, filepart2);
		Format[] testFormats = { fileform2, null, NumberFormat.getInstance() };
		MessageFormat pattform = new MessageFormat("There {0} on {1}");
		pattform.setFormats(testFormats);
		Object[] testArgs2 = { null, "ADisk", null };
		for (int i = 0; i < 4; ++i) {
			testArgs2[0] = new Integer(i);
			testArgs2[2] = testArgs2[0];
			System.out.println(pattform.format(testArgs2));
		}

		ChoiceFormat fmt = new ChoiceFormat(
				"-1#is negative| 0#is zero or fraction | 1#is one |1.0<is 1+ |2#is two |2<is more than 2.");
		System.out.println("Formatter Pattern : " + fmt.toPattern());

		System.out.println("Format with -INF : "
				+ fmt.format(Double.NEGATIVE_INFINITY));
		System.out.println("Format with -1.0 : " + fmt.format(-1.0));
		System.out.println("Format with 0 : " + fmt.format(0));
		System.out.println("Format with 0.9 : " + fmt.format(0.9));
		System.out.println("Format with 1.0 : " + fmt.format(1));
		System.out.println("Format with 1.5 : " + fmt.format(1.5));
		System.out.println("Format with 2 : " + fmt.format(2));
		System.out.println("Format with 2.1 : " + fmt.format(2.1));
		System.out.println("Format with NaN : " + fmt.format(Double.NaN));
		System.out.println("Format with +INF : "
				+ fmt.format(Double.POSITIVE_INFINITY));

	}

}



output:
The disk "MyDisk" contains '1,333 files'.
0.0 -> Sun -> 1.0
1.0 -> Sun -> 1.0
2.0 -> Mon -> 2.0
3.0 -> Tue -> 3.0
4.0 -> Wed -> 4.0
5.0 -> Thur -> 5.0
6.0 -> Fri -> 6.0
7.0 -> Sat -> 7.0
8.0 -> Sat -> 7.0
There are no files on ADisk
There is one file on ADisk
There are 2 files on ADisk
There are 3 files on ADisk
Formatter Pattern : -1.0#is negative|0.0#is zero or fraction |1.0#is one |1.0<is 1+ |2.0#is two |2.0<is more than 2.
Format with -INF : is negative
Format with -1.0 : is negative
Format with 0 : is zero or fraction 
Format with 0.9 : is zero or fraction 
Format with 1.0 : is one 
Format with 1.5 : is 1+ 
Format with 2 : is two 
Format with 2.1 : is more than 2.
Format with NaN : is negative
Format with +INF : is more than 2.


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。