Appendable接口的实现类的对象能够被添加 char 序列和值。如果某个类的实例打算接收取自 java.util.Formatter 的格式化输出,那么该类必须实现 Appendable 接口。 要添加的字符应该是有效的 Unicode 字符。 Appendable 对于多线程访问而言没必要是安全的。线程安全由扩展和实现此接口的类负责。 所有已知实现类: BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer 所期望用法的示例: StringBuilder sb = new StringBuilder(); // StringBuilder实现了Appendable接口 // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. // 将格式化后的字符串放入sb formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // Optional locale as the first argument can be used to get // locale-specific formatting of numbers. The precision and width can be // given to round and align the value. formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); // -> "e = +2,7183" // The '(' numeric flag may be used to format negative numbers with // parentheses rather than a minus sign. Group separators are // automatically inserted. formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta); // -> "Amount gained or lost since last statement: $ (6,217.58)" 常见格式化请求的便捷方法是按照如下调用格式来阐明的: // Writes a formatted string to System.out. System.out.format("Local time: %tT", Calendar.getInstance()); // -> "Local time: 13:34:18" // Writes formatted output to System.err. System.err.printf("Unable to open file '%1$s': %2$s", fileName, exception.getMessage()); // -> "Unable to open file 'food': No such file or directory" 与 C 语言的 sprintf(3) 类似,可以使用静态方法 String.format(String,Object...) 来格式化 Strings: // Format a string containing a date. import java.util.Calendar; import java.util.GregorianCalendar; import static java.util.Calendar.*; Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke's Birthday: May 23, 1995" java.lang.Appendable接口方法
|
|