public interface Formattable
Formatter
执行类实现。此接口允许对任意对象进行格式化的基本控件。例如,下面的类打印出股票的名称的不同表示不同的旗帜和长度的限制:
import java.nio.CharBuffer; import java.util.Formatter; import java.util.Formattable; import java.util.Locale; import static java.util.FormattableFlags.*; ... public class StockName implements Formattable { private String symbol, companyName, frenchCompanyName; public StockName(String symbol, String companyName, String frenchCompanyName) { ... } ... public void formatTo(Formatter fmt, int f, int width, int precision) { StringBuilder sb = new StringBuilder(); // decide form of name String name = companyName; if (fmt.locale().equals(Locale.FRANCE)) name = frenchCompanyName; boolean alternate = (f & ALTERNATE) == ALTERNATE; boolean usesymbol = alternate || (precision != -1 && precision < 10); String out = (usesymbol ? symbol : name); // apply precision if (precision == -1 || out.length() < precision) { // write it all sb.append(out); } else { sb.append(out.substring(0, precision - 1)).append('*'); } // apply width and justification int len = sb.length(); if (len < width) for (int i = 0; i < width - len; i++) if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY) sb.append(' '); else sb.insert(0, ' '); fmt.format(sb.toString()); } public String toString() { return String.format("%s - %s", symbol, companyName); } }
当使用与Formatter
连接,上述类产生以下各种格式字符串输出。Formatter fmt = new Formatter(); StockName sn = new StockName("HUGE", "Huge Fruit, Inc.", "Fruit Titanesque, Inc."); fmt.format("%s", sn); // -> "Huge Fruit, Inc." fmt.format("%s", sn.toString()); // -> "HUGE - Huge Fruit, Inc." fmt.format("%#s", sn); // -> "HUGE" fmt.format("%-10.8s", sn); // -> "HUGE " fmt.format("%.12s", sn); // -> "Huge Fruit,*" fmt.format(Locale.FRANCE, "%25s", sn); // -> " Fruit Titanesque, Inc."
formattables未必是安全的多线程访问。线程安全是可选的,可以通过扩展和实现此接口的类来执行。
除非另有规定,通过null争论在这个接口的所有方法会导致NullPointerException
被。
void formatTo(Formatter formatter, int flags, int width, int precision)
formatter
对象格式。
formatter
-
formatter
。实现类可以调用
formatter.out()
或
formatter.locale()
获得使用
formatter分别
Appendable
或
Locale
。
flags
的旗帜修改输出格式。该值被解释为一个位掩码。以下标志的任何组合可以设置:
FormattableFlags.LEFT_JUSTIFY
,
FormattableFlags.UPPERCASE
,和
FormattableFlags.ALTERNATE
。如果未设置任何标志,将使用默认格式的实现类。
width
-字符的最小数目被写入到输出。如果转换后的值的长度小于
width然后输出将被填充的
' '直到字符总数等于宽度。填充在默认情况下是在开始的。如果
FormattableFlags.LEFT_JUSTIFY
标志被设置,然后填充将在年底。如果
width是
-1然后没有最低。
precision
-最大字符数被写入到输出。精度应用前的宽度,从而输出将被截断
precision人物即使
width大于
precision。如果
precision是
-1然后在字符的数量没有明确的限制。
IllegalFormatException
-如果任何参数无效。对于所有可能的格式错误的规范,看到格式化程序类规范的
Details节。
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.