Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Formatter.java
38829 views
/*1* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.io.BufferedWriter;28import java.io.Closeable;29import java.io.IOException;30import java.io.File;31import java.io.FileOutputStream;32import java.io.FileNotFoundException;33import java.io.Flushable;34import java.io.OutputStream;35import java.io.OutputStreamWriter;36import java.io.PrintStream;37import java.io.UnsupportedEncodingException;38import java.math.BigDecimal;39import java.math.BigInteger;40import java.math.MathContext;41import java.math.RoundingMode;42import java.nio.charset.Charset;43import java.nio.charset.IllegalCharsetNameException;44import java.nio.charset.UnsupportedCharsetException;45import java.text.DateFormatSymbols;46import java.text.DecimalFormat;47import java.text.DecimalFormatSymbols;48import java.text.NumberFormat;49import java.util.regex.Matcher;50import java.util.regex.Pattern;5152import java.time.DateTimeException;53import java.time.Instant;54import java.time.ZoneId;55import java.time.ZoneOffset;56import java.time.temporal.ChronoField;57import java.time.temporal.TemporalAccessor;58import java.time.temporal.TemporalQueries;5960import sun.misc.DoubleConsts;61import sun.misc.FormattedFloatingDecimal;6263/**64* An interpreter for printf-style format strings. This class provides support65* for layout justification and alignment, common formats for numeric, string,66* and date/time data, and locale-specific output. Common Java types such as67* {@code byte}, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar}68* are supported. Limited formatting customization for arbitrary user types is69* provided through the {@link Formattable} interface.70*71* <p> Formatters are not necessarily safe for multithreaded access. Thread72* safety is optional and is the responsibility of users of methods in this73* class.74*75* <p> Formatted printing for the Java language is heavily inspired by C's76* {@code printf}. Although the format strings are similar to C, some77* customizations have been made to accommodate the Java language and exploit78* some of its features. Also, Java formatting is more strict than C's; for79* example, if a conversion is incompatible with a flag, an exception will be80* thrown. In C inapplicable flags are silently ignored. The format strings81* are thus intended to be recognizable to C programmers but not necessarily82* completely compatible with those in C.83*84* <p> Examples of expected usage:85*86* <blockquote><pre>87* StringBuilder sb = new StringBuilder();88* // Send all output to the Appendable object sb89* Formatter formatter = new Formatter(sb, Locale.US);90*91* // Explicit argument indices may be used to re-order output.92* formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")93* // -> " d c b a"94*95* // Optional locale as the first argument can be used to get96* // locale-specific formatting of numbers. The precision and width can be97* // given to round and align the value.98* formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);99* // -> "e = +2,7183"100*101* // The '(' numeric flag may be used to format negative numbers with102* // parentheses rather than a minus sign. Group separators are103* // automatically inserted.104* formatter.format("Amount gained or lost since last statement: $ %(,.2f",105* balanceDelta);106* // -> "Amount gained or lost since last statement: $ (6,217.58)"107* </pre></blockquote>108*109* <p> Convenience methods for common formatting requests exist as illustrated110* by the following invocations:111*112* <blockquote><pre>113* // Writes a formatted string to System.out.114* System.out.format("Local time: %tT", Calendar.getInstance());115* // -> "Local time: 13:34:18"116*117* // Writes formatted output to System.err.118* System.err.printf("Unable to open file '%1$s': %2$s",119* fileName, exception.getMessage());120* // -> "Unable to open file 'food': No such file or directory"121* </pre></blockquote>122*123* <p> Like C's {@code sprintf(3)}, Strings may be formatted using the static124* method {@link String#format(String,Object...) String.format}:125*126* <blockquote><pre>127* // Format a string containing a date.128* import java.util.Calendar;129* import java.util.GregorianCalendar;130* import static java.util.Calendar.*;131*132* Calendar c = new GregorianCalendar(1995, MAY, 23);133* String s = String.format("Duke's Birthday: %1$tb %1$te, %1$tY", c);134* // -> s == "Duke's Birthday: May 23, 1995"135* </pre></blockquote>136*137* <h3><a name="org">Organization</a></h3>138*139* <p> This specification is divided into two sections. The first section, <a140* href="#summary">Summary</a>, covers the basic formatting concepts. This141* section is intended for users who want to get started quickly and are142* familiar with formatted printing in other programming languages. The second143* section, <a href="#detail">Details</a>, covers the specific implementation144* details. It is intended for users who want more precise specification of145* formatting behavior.146*147* <h3><a name="summary">Summary</a></h3>148*149* <p> This section is intended to provide a brief overview of formatting150* concepts. For precise behavioral details, refer to the <a151* href="#detail">Details</a> section.152*153* <h4><a name="syntax">Format String Syntax</a></h4>154*155* <p> Every method which produces formatted output requires a <i>format156* string</i> and an <i>argument list</i>. The format string is a {@link157* String} which may contain fixed text and one or more embedded <i>format158* specifiers</i>. Consider the following example:159*160* <blockquote><pre>161* Calendar c = ...;162* String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);163* </pre></blockquote>164*165* This format string is the first argument to the {@code format} method. It166* contains three format specifiers "{@code %1$tm}", "{@code %1$te}", and167* "{@code %1$tY}" which indicate how the arguments should be processed and168* where they should be inserted in the text. The remaining portions of the169* format string are fixed text including {@code "Dukes Birthday: "} and any170* other spaces or punctuation.171*172* The argument list consists of all arguments passed to the method after the173* format string. In the above example, the argument list is of size one and174* consists of the {@link java.util.Calendar Calendar} object {@code c}.175*176* <ul>177*178* <li> The format specifiers for general, character, and numeric types have179* the following syntax:180*181* <blockquote><pre>182* %[argument_index$][flags][width][.precision]conversion183* </pre></blockquote>184*185* <p> The optional <i>argument_index</i> is a decimal integer indicating the186* position of the argument in the argument list. The first argument is187* referenced by "{@code 1$}", the second by "{@code 2$}", etc.188*189* <p> The optional <i>flags</i> is a set of characters that modify the output190* format. The set of valid flags depends on the conversion.191*192* <p> The optional <i>width</i> is a positive decimal integer indicating193* the minimum number of characters to be written to the output.194*195* <p> The optional <i>precision</i> is a non-negative decimal integer usually196* used to restrict the number of characters. The specific behavior depends on197* the conversion.198*199* <p> The required <i>conversion</i> is a character indicating how the200* argument should be formatted. The set of valid conversions for a given201* argument depends on the argument's data type.202*203* <li> The format specifiers for types which are used to represents dates and204* times have the following syntax:205*206* <blockquote><pre>207* %[argument_index$][flags][width]conversion208* </pre></blockquote>209*210* <p> The optional <i>argument_index</i>, <i>flags</i> and <i>width</i> are211* defined as above.212*213* <p> The required <i>conversion</i> is a two character sequence. The first214* character is {@code 't'} or {@code 'T'}. The second character indicates215* the format to be used. These characters are similar to but not completely216* identical to those defined by GNU {@code date} and POSIX217* {@code strftime(3c)}.218*219* <li> The format specifiers which do not correspond to arguments have the220* following syntax:221*222* <blockquote><pre>223* %[flags][width]conversion224* </pre></blockquote>225*226* <p> The optional <i>flags</i> and <i>width</i> is defined as above.227*228* <p> The required <i>conversion</i> is a character indicating content to be229* inserted in the output.230*231* </ul>232*233* <h4> Conversions </h4>234*235* <p> Conversions are divided into the following categories:236*237* <ol>238*239* <li> <b>General</b> - may be applied to any argument240* type241*242* <li> <b>Character</b> - may be applied to basic types which represent243* Unicode characters: {@code char}, {@link Character}, {@code byte}, {@link244* Byte}, {@code short}, and {@link Short}. This conversion may also be245* applied to the types {@code int} and {@link Integer} when {@link246* Character#isValidCodePoint} returns {@code true}247*248* <li> <b>Numeric</b>249*250* <ol>251*252* <li> <b>Integral</b> - may be applied to Java integral types: {@code byte},253* {@link Byte}, {@code short}, {@link Short}, {@code int} and {@link254* Integer}, {@code long}, {@link Long}, and {@link java.math.BigInteger255* BigInteger} (but not {@code char} or {@link Character})256*257* <li><b>Floating Point</b> - may be applied to Java floating-point types:258* {@code float}, {@link Float}, {@code double}, {@link Double}, and {@link259* java.math.BigDecimal BigDecimal}260*261* </ol>262*263* <li> <b>Date/Time</b> - may be applied to Java types which are capable of264* encoding a date or time: {@code long}, {@link Long}, {@link Calendar},265* {@link Date} and {@link TemporalAccessor TemporalAccessor}266*267* <li> <b>Percent</b> - produces a literal {@code '%'}268* (<tt>'\u0025'</tt>)269*270* <li> <b>Line Separator</b> - produces the platform-specific line separator271*272* </ol>273*274* <p> The following table summarizes the supported conversions. Conversions275* denoted by an upper-case character (i.e. {@code 'B'}, {@code 'H'},276* {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'}, {@code 'G'},277* {@code 'A'}, and {@code 'T'}) are the same as those for the corresponding278* lower-case conversion characters except that the result is converted to279* upper case according to the rules of the prevailing {@link java.util.Locale280* Locale}. The result is equivalent to the following invocation of {@link281* String#toUpperCase()}282*283* <pre>284* out.toUpperCase() </pre>285*286* <table cellpadding=5 summary="genConv">287*288* <tr><th valign="bottom"> Conversion289* <th valign="bottom"> Argument Category290* <th valign="bottom"> Description291*292* <tr><td valign="top"> {@code 'b'}, {@code 'B'}293* <td valign="top"> general294* <td> If the argument <i>arg</i> is {@code null}, then the result is295* "{@code false}". If <i>arg</i> is a {@code boolean} or {@link296* Boolean}, then the result is the string returned by {@link297* String#valueOf(boolean) String.valueOf(arg)}. Otherwise, the result is298* "true".299*300* <tr><td valign="top"> {@code 'h'}, {@code 'H'}301* <td valign="top"> general302* <td> If the argument <i>arg</i> is {@code null}, then the result is303* "{@code null}". Otherwise, the result is obtained by invoking304* {@code Integer.toHexString(arg.hashCode())}.305*306* <tr><td valign="top"> {@code 's'}, {@code 'S'}307* <td valign="top"> general308* <td> If the argument <i>arg</i> is {@code null}, then the result is309* "{@code null}". If <i>arg</i> implements {@link Formattable}, then310* {@link Formattable#formatTo arg.formatTo} is invoked. Otherwise, the311* result is obtained by invoking {@code arg.toString()}.312*313* <tr><td valign="top">{@code 'c'}, {@code 'C'}314* <td valign="top"> character315* <td> The result is a Unicode character316*317* <tr><td valign="top">{@code 'd'}318* <td valign="top"> integral319* <td> The result is formatted as a decimal integer320*321* <tr><td valign="top">{@code 'o'}322* <td valign="top"> integral323* <td> The result is formatted as an octal integer324*325* <tr><td valign="top">{@code 'x'}, {@code 'X'}326* <td valign="top"> integral327* <td> The result is formatted as a hexadecimal integer328*329* <tr><td valign="top">{@code 'e'}, {@code 'E'}330* <td valign="top"> floating point331* <td> The result is formatted as a decimal number in computerized332* scientific notation333*334* <tr><td valign="top">{@code 'f'}335* <td valign="top"> floating point336* <td> The result is formatted as a decimal number337*338* <tr><td valign="top">{@code 'g'}, {@code 'G'}339* <td valign="top"> floating point340* <td> The result is formatted using computerized scientific notation or341* decimal format, depending on the precision and the value after rounding.342*343* <tr><td valign="top">{@code 'a'}, {@code 'A'}344* <td valign="top"> floating point345* <td> The result is formatted as a hexadecimal floating-point number with346* a significand and an exponent. This conversion is <b>not</b> supported347* for the {@code BigDecimal} type despite the latter's being in the348* <i>floating point</i> argument category.349*350* <tr><td valign="top">{@code 't'}, {@code 'T'}351* <td valign="top"> date/time352* <td> Prefix for date and time conversion characters. See <a353* href="#dt">Date/Time Conversions</a>.354*355* <tr><td valign="top">{@code '%'}356* <td valign="top"> percent357* <td> The result is a literal {@code '%'} (<tt>'\u0025'</tt>)358*359* <tr><td valign="top">{@code 'n'}360* <td valign="top"> line separator361* <td> The result is the platform-specific line separator362*363* </table>364*365* <p> Any characters not explicitly defined as conversions are illegal and are366* reserved for future extensions.367*368* <h4><a name="dt">Date/Time Conversions</a></h4>369*370* <p> The following date and time conversion suffix characters are defined for371* the {@code 't'} and {@code 'T'} conversions. The types are similar to but372* not completely identical to those defined by GNU {@code date} and POSIX373* {@code strftime(3c)}. Additional conversion types are provided to access374* Java-specific functionality (e.g. {@code 'L'} for milliseconds within the375* second).376*377* <p> The following conversion characters are used for formatting times:378*379* <table cellpadding=5 summary="time">380*381* <tr><td valign="top"> {@code 'H'}382* <td> Hour of the day for the 24-hour clock, formatted as two digits with383* a leading zero as necessary i.e. {@code 00 - 23}.384*385* <tr><td valign="top">{@code 'I'}386* <td> Hour for the 12-hour clock, formatted as two digits with a leading387* zero as necessary, i.e. {@code 01 - 12}.388*389* <tr><td valign="top">{@code 'k'}390* <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}.391*392* <tr><td valign="top">{@code 'l'}393* <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}.394*395* <tr><td valign="top">{@code 'M'}396* <td> Minute within the hour formatted as two digits with a leading zero397* as necessary, i.e. {@code 00 - 59}.398*399* <tr><td valign="top">{@code 'S'}400* <td> Seconds within the minute, formatted as two digits with a leading401* zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special402* value required to support leap seconds).403*404* <tr><td valign="top">{@code 'L'}405* <td> Millisecond within the second formatted as three digits with406* leading zeros as necessary, i.e. {@code 000 - 999}.407*408* <tr><td valign="top">{@code 'N'}409* <td> Nanosecond within the second, formatted as nine digits with leading410* zeros as necessary, i.e. {@code 000000000 - 999999999}.411*412* <tr><td valign="top">{@code 'p'}413* <td> Locale-specific {@linkplain414* java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker415* in lower case, e.g."{@code am}" or "{@code pm}". Use of the conversion416* prefix {@code 'T'} forces this output to upper case.417*418* <tr><td valign="top">{@code 'z'}419* <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a>420* style numeric time zone offset from GMT, e.g. {@code -0800}. This421* value will be adjusted as necessary for Daylight Saving Time. For422* {@code long}, {@link Long}, and {@link Date} the time zone used is423* the {@linkplain TimeZone#getDefault() default time zone} for this424* instance of the Java virtual machine.425*426* <tr><td valign="top">{@code 'Z'}427* <td> A string representing the abbreviation for the time zone. This428* value will be adjusted as necessary for Daylight Saving Time. For429* {@code long}, {@link Long}, and {@link Date} the time zone used is430* the {@linkplain TimeZone#getDefault() default time zone} for this431* instance of the Java virtual machine. The Formatter's locale will432* supersede the locale of the argument (if any).433*434* <tr><td valign="top">{@code 's'}435* <td> Seconds since the beginning of the epoch starting at 1 January 1970436* {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to437* {@code Long.MAX_VALUE/1000}.438*439* <tr><td valign="top">{@code 'Q'}440* <td> Milliseconds since the beginning of the epoch starting at 1 January441* 1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to442* {@code Long.MAX_VALUE}.443*444* </table>445*446* <p> The following conversion characters are used for formatting dates:447*448* <table cellpadding=5 summary="date">449*450* <tr><td valign="top">{@code 'B'}451* <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths452* full month name}, e.g. {@code "January"}, {@code "February"}.453*454* <tr><td valign="top">{@code 'b'}455* <td> Locale-specific {@linkplain456* java.text.DateFormatSymbols#getShortMonths abbreviated month name},457* e.g. {@code "Jan"}, {@code "Feb"}.458*459* <tr><td valign="top">{@code 'h'}460* <td> Same as {@code 'b'}.461*462* <tr><td valign="top">{@code 'A'}463* <td> Locale-specific full name of the {@linkplain464* java.text.DateFormatSymbols#getWeekdays day of the week},465* e.g. {@code "Sunday"}, {@code "Monday"}466*467* <tr><td valign="top">{@code 'a'}468* <td> Locale-specific short name of the {@linkplain469* java.text.DateFormatSymbols#getShortWeekdays day of the week},470* e.g. {@code "Sun"}, {@code "Mon"}471*472* <tr><td valign="top">{@code 'C'}473* <td> Four-digit year divided by {@code 100}, formatted as two digits474* with leading zero as necessary, i.e. {@code 00 - 99}475*476* <tr><td valign="top">{@code 'Y'}477* <td> Year, formatted as at least four digits with leading zeros as478* necessary, e.g. {@code 0092} equals {@code 92} CE for the Gregorian479* calendar.480*481* <tr><td valign="top">{@code 'y'}482* <td> Last two digits of the year, formatted with leading zeros as483* necessary, i.e. {@code 00 - 99}.484*485* <tr><td valign="top">{@code 'j'}486* <td> Day of year, formatted as three digits with leading zeros as487* necessary, e.g. {@code 001 - 366} for the Gregorian calendar.488*489* <tr><td valign="top">{@code 'm'}490* <td> Month, formatted as two digits with leading zeros as necessary,491* i.e. {@code 01 - 13}.492*493* <tr><td valign="top">{@code 'd'}494* <td> Day of month, formatted as two digits with leading zeros as495* necessary, i.e. {@code 01 - 31}496*497* <tr><td valign="top">{@code 'e'}498* <td> Day of month, formatted as two digits, i.e. {@code 1 - 31}.499*500* </table>501*502* <p> The following conversion characters are used for formatting common503* date/time compositions.504*505* <table cellpadding=5 summary="composites">506*507* <tr><td valign="top">{@code 'R'}508* <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"}509*510* <tr><td valign="top">{@code 'T'}511* <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}.512*513* <tr><td valign="top">{@code 'r'}514* <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS %Tp"}.515* The location of the morning or afternoon marker ({@code '%Tp'}) may be516* locale-dependent.517*518* <tr><td valign="top">{@code 'D'}519* <td> Date formatted as {@code "%tm/%td/%ty"}.520*521* <tr><td valign="top">{@code 'F'}522* <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a>523* complete date formatted as {@code "%tY-%tm-%td"}.524*525* <tr><td valign="top">{@code 'c'}526* <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"},527* e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}.528*529* </table>530*531* <p> Any characters not explicitly defined as date/time conversion suffixes532* are illegal and are reserved for future extensions.533*534* <h4> Flags </h4>535*536* <p> The following table summarizes the supported flags. <i>y</i> means the537* flag is supported for the indicated argument types.538*539* <table cellpadding=5 summary="genConv">540*541* <tr><th valign="bottom"> Flag <th valign="bottom"> General542* <th valign="bottom"> Character <th valign="bottom"> Integral543* <th valign="bottom"> Floating Point544* <th valign="bottom"> Date/Time545* <th valign="bottom"> Description546*547* <tr><td> '-' <td align="center" valign="top"> y548* <td align="center" valign="top"> y549* <td align="center" valign="top"> y550* <td align="center" valign="top"> y551* <td align="center" valign="top"> y552* <td> The result will be left-justified.553*554* <tr><td> '#' <td align="center" valign="top"> y<sup>1</sup>555* <td align="center" valign="top"> -556* <td align="center" valign="top"> y<sup>3</sup>557* <td align="center" valign="top"> y558* <td align="center" valign="top"> -559* <td> The result should use a conversion-dependent alternate form560*561* <tr><td> '+' <td align="center" valign="top"> -562* <td align="center" valign="top"> -563* <td align="center" valign="top"> y<sup>4</sup>564* <td align="center" valign="top"> y565* <td align="center" valign="top"> -566* <td> The result will always include a sign567*568* <tr><td> ' ' <td align="center" valign="top"> -569* <td align="center" valign="top"> -570* <td align="center" valign="top"> y<sup>4</sup>571* <td align="center" valign="top"> y572* <td align="center" valign="top"> -573* <td> The result will include a leading space for positive values574*575* <tr><td> '0' <td align="center" valign="top"> -576* <td align="center" valign="top"> -577* <td align="center" valign="top"> y578* <td align="center" valign="top"> y579* <td align="center" valign="top"> -580* <td> The result will be zero-padded581*582* <tr><td> ',' <td align="center" valign="top"> -583* <td align="center" valign="top"> -584* <td align="center" valign="top"> y<sup>2</sup>585* <td align="center" valign="top"> y<sup>5</sup>586* <td align="center" valign="top"> -587* <td> The result will include locale-specific {@linkplain588* java.text.DecimalFormatSymbols#getGroupingSeparator grouping separators}589*590* <tr><td> '(' <td align="center" valign="top"> -591* <td align="center" valign="top"> -592* <td align="center" valign="top"> y<sup>4</sup>593* <td align="center" valign="top"> y<sup>5</sup>594* <td align="center"> -595* <td> The result will enclose negative numbers in parentheses596*597* </table>598*599* <p> <sup>1</sup> Depends on the definition of {@link Formattable}.600*601* <p> <sup>2</sup> For {@code 'd'} conversion only.602*603* <p> <sup>3</sup> For {@code 'o'}, {@code 'x'}, and {@code 'X'}604* conversions only.605*606* <p> <sup>4</sup> For {@code 'd'}, {@code 'o'}, {@code 'x'}, and607* {@code 'X'} conversions applied to {@link java.math.BigInteger BigInteger}608* or {@code 'd'} applied to {@code byte}, {@link Byte}, {@code short}, {@link609* Short}, {@code int} and {@link Integer}, {@code long}, and {@link Long}.610*611* <p> <sup>5</sup> For {@code 'e'}, {@code 'E'}, {@code 'f'},612* {@code 'g'}, and {@code 'G'} conversions only.613*614* <p> Any characters not explicitly defined as flags are illegal and are615* reserved for future extensions.616*617* <h4> Width </h4>618*619* <p> The width is the minimum number of characters to be written to the620* output. For the line separator conversion, width is not applicable; if it621* is provided, an exception will be thrown.622*623* <h4> Precision </h4>624*625* <p> For general argument types, the precision is the maximum number of626* characters to be written to the output.627*628* <p> For the floating-point conversions {@code 'a'}, {@code 'A'}, {@code 'e'},629* {@code 'E'}, and {@code 'f'} the precision is the number of digits after the630* radix point. If the conversion is {@code 'g'} or {@code 'G'}, then the631* precision is the total number of digits in the resulting magnitude after632* rounding.633*634* <p> For character, integral, and date/time argument types and the percent635* and line separator conversions, the precision is not applicable; if a636* precision is provided, an exception will be thrown.637*638* <h4> Argument Index </h4>639*640* <p> The argument index is a decimal integer indicating the position of the641* argument in the argument list. The first argument is referenced by642* "{@code 1$}", the second by "{@code 2$}", etc.643*644* <p> Another way to reference arguments by position is to use the645* {@code '<'} (<tt>'\u003c'</tt>) flag, which causes the argument for646* the previous format specifier to be re-used. For example, the following two647* statements would produce identical strings:648*649* <blockquote><pre>650* Calendar c = ...;651* String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);652*653* String s2 = String.format("Duke's Birthday: %1$tm %<te,%<tY", c);654* </pre></blockquote>655*656* <hr>657* <h3><a name="detail">Details</a></h3>658*659* <p> This section is intended to provide behavioral details for formatting,660* including conditions and exceptions, supported data types, localization, and661* interactions between flags, conversions, and data types. For an overview of662* formatting concepts, refer to the <a href="#summary">Summary</a>663*664* <p> Any characters not explicitly defined as conversions, date/time665* conversion suffixes, or flags are illegal and are reserved for666* future extensions. Use of such a character in a format string will667* cause an {@link UnknownFormatConversionException} or {@link668* UnknownFormatFlagsException} to be thrown.669*670* <p> If the format specifier contains a width or precision with an invalid671* value or which is otherwise unsupported, then a {@link672* IllegalFormatWidthException} or {@link IllegalFormatPrecisionException}673* respectively will be thrown.674*675* <p> If a format specifier contains a conversion character that is not676* applicable to the corresponding argument, then an {@link677* IllegalFormatConversionException} will be thrown.678*679* <p> All specified exceptions may be thrown by any of the {@code format}680* methods of {@code Formatter} as well as by any {@code format} convenience681* methods such as {@link String#format(String,Object...) String.format} and682* {@link java.io.PrintStream#printf(String,Object...) PrintStream.printf}.683*684* <p> Conversions denoted by an upper-case character (i.e. {@code 'B'},685* {@code 'H'}, {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'},686* {@code 'G'}, {@code 'A'}, and {@code 'T'}) are the same as those for the687* corresponding lower-case conversion characters except that the result is688* converted to upper case according to the rules of the prevailing {@link689* java.util.Locale Locale}. The result is equivalent to the following690* invocation of {@link String#toUpperCase()}691*692* <pre>693* out.toUpperCase() </pre>694*695* <h4><a name="dgen">General</a></h4>696*697* <p> The following general conversions may be applied to any argument type:698*699* <table cellpadding=5 summary="dgConv">700*701* <tr><td valign="top"> {@code 'b'}702* <td valign="top"> <tt>'\u0062'</tt>703* <td> Produces either "{@code true}" or "{@code false}" as returned by704* {@link Boolean#toString(boolean)}.705*706* <p> If the argument is {@code null}, then the result is707* "{@code false}". If the argument is a {@code boolean} or {@link708* Boolean}, then the result is the string returned by {@link709* String#valueOf(boolean) String.valueOf()}. Otherwise, the result is710* "{@code true}".711*712* <p> If the {@code '#'} flag is given, then a {@link713* FormatFlagsConversionMismatchException} will be thrown.714*715* <tr><td valign="top"> {@code 'B'}716* <td valign="top"> <tt>'\u0042'</tt>717* <td> The upper-case variant of {@code 'b'}.718*719* <tr><td valign="top"> {@code 'h'}720* <td valign="top"> <tt>'\u0068'</tt>721* <td> Produces a string representing the hash code value of the object.722*723* <p> If the argument, <i>arg</i> is {@code null}, then the724* result is "{@code null}". Otherwise, the result is obtained725* by invoking {@code Integer.toHexString(arg.hashCode())}.726*727* <p> If the {@code '#'} flag is given, then a {@link728* FormatFlagsConversionMismatchException} will be thrown.729*730* <tr><td valign="top"> {@code 'H'}731* <td valign="top"> <tt>'\u0048'</tt>732* <td> The upper-case variant of {@code 'h'}.733*734* <tr><td valign="top"> {@code 's'}735* <td valign="top"> <tt>'\u0073'</tt>736* <td> Produces a string.737*738* <p> If the argument is {@code null}, then the result is739* "{@code null}". If the argument implements {@link Formattable}, then740* its {@link Formattable#formatTo formatTo} method is invoked.741* Otherwise, the result is obtained by invoking the argument's742* {@code toString()} method.743*744* <p> If the {@code '#'} flag is given and the argument is not a {@link745* Formattable} , then a {@link FormatFlagsConversionMismatchException}746* will be thrown.747*748* <tr><td valign="top"> {@code 'S'}749* <td valign="top"> <tt>'\u0053'</tt>750* <td> The upper-case variant of {@code 's'}.751*752* </table>753*754* <p> The following <a name="dFlags">flags</a> apply to general conversions:755*756* <table cellpadding=5 summary="dFlags">757*758* <tr><td valign="top"> {@code '-'}759* <td valign="top"> <tt>'\u002d'</tt>760* <td> Left justifies the output. Spaces (<tt>'\u0020'</tt>) will be761* added at the end of the converted value as required to fill the minimum762* width of the field. If the width is not provided, then a {@link763* MissingFormatWidthException} will be thrown. If this flag is not given764* then the output will be right-justified.765*766* <tr><td valign="top"> {@code '#'}767* <td valign="top"> <tt>'\u0023'</tt>768* <td> Requires the output use an alternate form. The definition of the769* form is specified by the conversion.770*771* </table>772*773* <p> The <a name="genWidth">width</a> is the minimum number of characters to774* be written to the775* output. If the length of the converted value is less than the width then776* the output will be padded by <tt>' '</tt> (<tt>'\u0020'</tt>)777* until the total number of characters equals the width. The padding is on778* the left by default. If the {@code '-'} flag is given, then the padding779* will be on the right. If the width is not specified then there is no780* minimum.781*782* <p> The precision is the maximum number of characters to be written to the783* output. The precision is applied before the width, thus the output will be784* truncated to {@code precision} characters even if the width is greater than785* the precision. If the precision is not specified then there is no explicit786* limit on the number of characters.787*788* <h4><a name="dchar">Character</a></h4>789*790* This conversion may be applied to {@code char} and {@link Character}. It791* may also be applied to the types {@code byte}, {@link Byte},792* {@code short}, and {@link Short}, {@code int} and {@link Integer} when793* {@link Character#isValidCodePoint} returns {@code true}. If it returns794* {@code false} then an {@link IllegalFormatCodePointException} will be795* thrown.796*797* <table cellpadding=5 summary="charConv">798*799* <tr><td valign="top"> {@code 'c'}800* <td valign="top"> <tt>'\u0063'</tt>801* <td> Formats the argument as a Unicode character as described in <a802* href="../lang/Character.html#unicode">Unicode Character803* Representation</a>. This may be more than one 16-bit {@code char} in804* the case where the argument represents a supplementary character.805*806* <p> If the {@code '#'} flag is given, then a {@link807* FormatFlagsConversionMismatchException} will be thrown.808*809* <tr><td valign="top"> {@code 'C'}810* <td valign="top"> <tt>'\u0043'</tt>811* <td> The upper-case variant of {@code 'c'}.812*813* </table>814*815* <p> The {@code '-'} flag defined for <a href="#dFlags">General816* conversions</a> applies. If the {@code '#'} flag is given, then a {@link817* FormatFlagsConversionMismatchException} will be thrown.818*819* <p> The width is defined as for <a href="#genWidth">General conversions</a>.820*821* <p> The precision is not applicable. If the precision is specified then an822* {@link IllegalFormatPrecisionException} will be thrown.823*824* <h4><a name="dnum">Numeric</a></h4>825*826* <p> Numeric conversions are divided into the following categories:827*828* <ol>829*830* <li> <a href="#dnint"><b>Byte, Short, Integer, and Long</b></a>831*832* <li> <a href="#dnbint"><b>BigInteger</b></a>833*834* <li> <a href="#dndec"><b>Float and Double</b></a>835*836* <li> <a href="#dnbdec"><b>BigDecimal</b></a>837*838* </ol>839*840* <p> Numeric types will be formatted according to the following algorithm:841*842* <p><b><a name="L10nAlgorithm"> Number Localization Algorithm</a></b>843*844* <p> After digits are obtained for the integer part, fractional part, and845* exponent (as appropriate for the data type), the following transformation846* is applied:847*848* <ol>849*850* <li> Each digit character <i>d</i> in the string is replaced by a851* locale-specific digit computed relative to the current locale's852* {@linkplain java.text.DecimalFormatSymbols#getZeroDigit() zero digit}853* <i>z</i>; that is <i>d - </i> {@code '0'}854* <i> + z</i>.855*856* <li> If a decimal separator is present, a locale-specific {@linkplain857* java.text.DecimalFormatSymbols#getDecimalSeparator decimal separator} is858* substituted.859*860* <li> If the {@code ','} (<tt>'\u002c'</tt>)861* <a name="L10nGroup">flag</a> is given, then the locale-specific {@linkplain862* java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is863* inserted by scanning the integer part of the string from least significant864* to most significant digits and inserting a separator at intervals defined by865* the locale's {@linkplain java.text.DecimalFormat#getGroupingSize() grouping866* size}.867*868* <li> If the {@code '0'} flag is given, then the locale-specific {@linkplain869* java.text.DecimalFormatSymbols#getZeroDigit() zero digits} are inserted870* after the sign character, if any, and before the first non-zero digit, until871* the length of the string is equal to the requested field width.872*873* <li> If the value is negative and the {@code '('} flag is given, then a874* {@code '('} (<tt>'\u0028'</tt>) is prepended and a {@code ')'}875* (<tt>'\u0029'</tt>) is appended.876*877* <li> If the value is negative (or floating-point negative zero) and878* {@code '('} flag is not given, then a {@code '-'} (<tt>'\u002d'</tt>)879* is prepended.880*881* <li> If the {@code '+'} flag is given and the value is positive or zero (or882* floating-point positive zero), then a {@code '+'} (<tt>'\u002b'</tt>)883* will be prepended.884*885* </ol>886*887* <p> If the value is NaN or positive infinity the literal strings "NaN" or888* "Infinity" respectively, will be output. If the value is negative infinity,889* then the output will be "(Infinity)" if the {@code '('} flag is given890* otherwise the output will be "-Infinity". These values are not localized.891*892* <p><a name="dnint"><b> Byte, Short, Integer, and Long </b></a>893*894* <p> The following conversions may be applied to {@code byte}, {@link Byte},895* {@code short}, {@link Short}, {@code int} and {@link Integer},896* {@code long}, and {@link Long}.897*898* <table cellpadding=5 summary="IntConv">899*900* <tr><td valign="top"> {@code 'd'}901* <td valign="top"> <tt>'\u0064'</tt>902* <td> Formats the argument as a decimal integer. The <a903* href="#L10nAlgorithm">localization algorithm</a> is applied.904*905* <p> If the {@code '0'} flag is given and the value is negative, then906* the zero padding will occur after the sign.907*908* <p> If the {@code '#'} flag is given then a {@link909* FormatFlagsConversionMismatchException} will be thrown.910*911* <tr><td valign="top"> {@code 'o'}912* <td valign="top"> <tt>'\u006f'</tt>913* <td> Formats the argument as an integer in base eight. No localization914* is applied.915*916* <p> If <i>x</i> is negative then the result will be an unsigned value917* generated by adding 2<sup>n</sup> to the value where {@code n} is the918* number of bits in the type as returned by the static {@code SIZE} field919* in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short},920* {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long}921* classes as appropriate.922*923* <p> If the {@code '#'} flag is given then the output will always begin924* with the radix indicator {@code '0'}.925*926* <p> If the {@code '0'} flag is given then the output will be padded927* with leading zeros to the field width following any indication of sign.928*929* <p> If {@code '('}, {@code '+'}, ' ', or {@code ','} flags930* are given then a {@link FormatFlagsConversionMismatchException} will be931* thrown.932*933* <tr><td valign="top"> {@code 'x'}934* <td valign="top"> <tt>'\u0078'</tt>935* <td> Formats the argument as an integer in base sixteen. No936* localization is applied.937*938* <p> If <i>x</i> is negative then the result will be an unsigned value939* generated by adding 2<sup>n</sup> to the value where {@code n} is the940* number of bits in the type as returned by the static {@code SIZE} field941* in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short},942* {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long}943* classes as appropriate.944*945* <p> If the {@code '#'} flag is given then the output will always begin946* with the radix indicator {@code "0x"}.947*948* <p> If the {@code '0'} flag is given then the output will be padded to949* the field width with leading zeros after the radix indicator or sign (if950* present).951*952* <p> If {@code '('}, <tt>' '</tt>, {@code '+'}, or953* {@code ','} flags are given then a {@link954* FormatFlagsConversionMismatchException} will be thrown.955*956* <tr><td valign="top"> {@code 'X'}957* <td valign="top"> <tt>'\u0058'</tt>958* <td> The upper-case variant of {@code 'x'}. The entire string959* representing the number will be converted to {@linkplain960* String#toUpperCase upper case} including the {@code 'x'} (if any) and961* all hexadecimal digits {@code 'a'} - {@code 'f'}962* (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>).963*964* </table>965*966* <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and967* both the {@code '#'} and the {@code '0'} flags are given, then result will968* contain the radix indicator ({@code '0'} for octal and {@code "0x"} or969* {@code "0X"} for hexadecimal), some number of zeros (based on the width),970* and the value.971*972* <p> If the {@code '-'} flag is not given, then the space padding will occur973* before the sign.974*975* <p> The following <a name="intFlags">flags</a> apply to numeric integral976* conversions:977*978* <table cellpadding=5 summary="intFlags">979*980* <tr><td valign="top"> {@code '+'}981* <td valign="top"> <tt>'\u002b'</tt>982* <td> Requires the output to include a positive sign for all positive983* numbers. If this flag is not given then only negative values will984* include a sign.985*986* <p> If both the {@code '+'} and <tt>' '</tt> flags are given987* then an {@link IllegalFormatFlagsException} will be thrown.988*989* <tr><td valign="top"> <tt>' '</tt>990* <td valign="top"> <tt>'\u0020'</tt>991* <td> Requires the output to include a single extra space992* (<tt>'\u0020'</tt>) for non-negative values.993*994* <p> If both the {@code '+'} and <tt>' '</tt> flags are given995* then an {@link IllegalFormatFlagsException} will be thrown.996*997* <tr><td valign="top"> {@code '0'}998* <td valign="top"> <tt>'\u0030'</tt>999* <td> Requires the output to be padded with leading {@linkplain1000* java.text.DecimalFormatSymbols#getZeroDigit zeros} to the minimum field1001* width following any sign or radix indicator except when converting NaN1002* or infinity. If the width is not provided, then a {@link1003* MissingFormatWidthException} will be thrown.1004*1005* <p> If both the {@code '-'} and {@code '0'} flags are given then an1006* {@link IllegalFormatFlagsException} will be thrown.1007*1008* <tr><td valign="top"> {@code ','}1009* <td valign="top"> <tt>'\u002c'</tt>1010* <td> Requires the output to include the locale-specific {@linkplain1011* java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as1012* described in the <a href="#L10nGroup">"group" section</a> of the1013* localization algorithm.1014*1015* <tr><td valign="top"> {@code '('}1016* <td valign="top"> <tt>'\u0028'</tt>1017* <td> Requires the output to prepend a {@code '('}1018* (<tt>'\u0028'</tt>) and append a {@code ')'}1019* (<tt>'\u0029'</tt>) to negative values.1020*1021* </table>1022*1023* <p> If no <a name="intdFlags">flags</a> are given the default formatting is1024* as follows:1025*1026* <ul>1027*1028* <li> The output is right-justified within the {@code width}1029*1030* <li> Negative numbers begin with a {@code '-'} (<tt>'\u002d'</tt>)1031*1032* <li> Positive numbers and zero do not include a sign or extra leading1033* space1034*1035* <li> No grouping separators are included1036*1037* </ul>1038*1039* <p> The <a name="intWidth">width</a> is the minimum number of characters to1040* be written to the output. This includes any signs, digits, grouping1041* separators, radix indicator, and parentheses. If the length of the1042* converted value is less than the width then the output will be padded by1043* spaces (<tt>'\u0020'</tt>) until the total number of characters equals1044* width. The padding is on the left by default. If {@code '-'} flag is1045* given then the padding will be on the right. If width is not specified then1046* there is no minimum.1047*1048* <p> The precision is not applicable. If precision is specified then an1049* {@link IllegalFormatPrecisionException} will be thrown.1050*1051* <p><a name="dnbint"><b> BigInteger </b></a>1052*1053* <p> The following conversions may be applied to {@link1054* java.math.BigInteger}.1055*1056* <table cellpadding=5 summary="BIntConv">1057*1058* <tr><td valign="top"> {@code 'd'}1059* <td valign="top"> <tt>'\u0064'</tt>1060* <td> Requires the output to be formatted as a decimal integer. The <a1061* href="#L10nAlgorithm">localization algorithm</a> is applied.1062*1063* <p> If the {@code '#'} flag is given {@link1064* FormatFlagsConversionMismatchException} will be thrown.1065*1066* <tr><td valign="top"> {@code 'o'}1067* <td valign="top"> <tt>'\u006f'</tt>1068* <td> Requires the output to be formatted as an integer in base eight.1069* No localization is applied.1070*1071* <p> If <i>x</i> is negative then the result will be a signed value1072* beginning with {@code '-'} (<tt>'\u002d'</tt>). Signed output is1073* allowed for this type because unlike the primitive types it is not1074* possible to create an unsigned equivalent without assuming an explicit1075* data-type size.1076*1077* <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given1078* then the result will begin with {@code '+'} (<tt>'\u002b'</tt>).1079*1080* <p> If the {@code '#'} flag is given then the output will always begin1081* with {@code '0'} prefix.1082*1083* <p> If the {@code '0'} flag is given then the output will be padded1084* with leading zeros to the field width following any indication of sign.1085*1086* <p> If the {@code ','} flag is given then a {@link1087* FormatFlagsConversionMismatchException} will be thrown.1088*1089* <tr><td valign="top"> {@code 'x'}1090* <td valign="top"> <tt>'\u0078'</tt>1091* <td> Requires the output to be formatted as an integer in base1092* sixteen. No localization is applied.1093*1094* <p> If <i>x</i> is negative then the result will be a signed value1095* beginning with {@code '-'} (<tt>'\u002d'</tt>). Signed output is1096* allowed for this type because unlike the primitive types it is not1097* possible to create an unsigned equivalent without assuming an explicit1098* data-type size.1099*1100* <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given1101* then the result will begin with {@code '+'} (<tt>'\u002b'</tt>).1102*1103* <p> If the {@code '#'} flag is given then the output will always begin1104* with the radix indicator {@code "0x"}.1105*1106* <p> If the {@code '0'} flag is given then the output will be padded to1107* the field width with leading zeros after the radix indicator or sign (if1108* present).1109*1110* <p> If the {@code ','} flag is given then a {@link1111* FormatFlagsConversionMismatchException} will be thrown.1112*1113* <tr><td valign="top"> {@code 'X'}1114* <td valign="top"> <tt>'\u0058'</tt>1115* <td> The upper-case variant of {@code 'x'}. The entire string1116* representing the number will be converted to {@linkplain1117* String#toUpperCase upper case} including the {@code 'x'} (if any) and1118* all hexadecimal digits {@code 'a'} - {@code 'f'}1119* (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>).1120*1121* </table>1122*1123* <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and1124* both the {@code '#'} and the {@code '0'} flags are given, then result will1125* contain the base indicator ({@code '0'} for octal and {@code "0x"} or1126* {@code "0X"} for hexadecimal), some number of zeros (based on the width),1127* and the value.1128*1129* <p> If the {@code '0'} flag is given and the value is negative, then the1130* zero padding will occur after the sign.1131*1132* <p> If the {@code '-'} flag is not given, then the space padding will occur1133* before the sign.1134*1135* <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and1136* Long apply. The <a href="#intdFlags">default behavior</a> when no flags are1137* given is the same as for Byte, Short, Integer, and Long.1138*1139* <p> The specification of <a href="#intWidth">width</a> is the same as1140* defined for Byte, Short, Integer, and Long.1141*1142* <p> The precision is not applicable. If precision is specified then an1143* {@link IllegalFormatPrecisionException} will be thrown.1144*1145* <p><a name="dndec"><b> Float and Double</b></a>1146*1147* <p> The following conversions may be applied to {@code float}, {@link1148* Float}, {@code double} and {@link Double}.1149*1150* <table cellpadding=5 summary="floatConv">1151*1152* <tr><td valign="top"> {@code 'e'}1153* <td valign="top"> <tt>'\u0065'</tt>1154* <td> Requires the output to be formatted using <a1155* name="scientific">computerized scientific notation</a>. The <a1156* href="#L10nAlgorithm">localization algorithm</a> is applied.1157*1158* <p> The formatting of the magnitude <i>m</i> depends upon its value.1159*1160* <p> If <i>m</i> is NaN or infinite, the literal strings "NaN" or1161* "Infinity", respectively, will be output. These values are not1162* localized.1163*1164* <p> If <i>m</i> is positive-zero or negative-zero, then the exponent1165* will be {@code "+00"}.1166*1167* <p> Otherwise, the result is a string that represents the sign and1168* magnitude (absolute value) of the argument. The formatting of the sign1169* is described in the <a href="#L10nAlgorithm">localization1170* algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its1171* value.1172*1173* <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup>1174* <= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the1175* mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so1176* that 1 <= <i>a</i> < 10. The magnitude is then represented as the1177* integer part of <i>a</i>, as a single decimal digit, followed by the1178* decimal separator followed by decimal digits representing the fractional1179* part of <i>a</i>, followed by the exponent symbol {@code 'e'}1180* (<tt>'\u0065'</tt>), followed by the sign of the exponent, followed1181* by a representation of <i>n</i> as a decimal integer, as produced by the1182* method {@link Long#toString(long, int)}, and zero-padded to include at1183* least two digits.1184*1185* <p> The number of digits in the result for the fractional part of1186* <i>m</i> or <i>a</i> is equal to the precision. If the precision is not1187* specified then the default value is {@code 6}. If the precision is less1188* than the number of digits which would appear after the decimal point in1189* the string returned by {@link Float#toString(float)} or {@link1190* Double#toString(double)} respectively, then the value will be rounded1191* using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up1192* algorithm}. Otherwise, zeros may be appended to reach the precision.1193* For a canonical representation of the value, use {@link1194* Float#toString(float)} or {@link Double#toString(double)} as1195* appropriate.1196*1197* <p>If the {@code ','} flag is given, then an {@link1198* FormatFlagsConversionMismatchException} will be thrown.1199*1200* <tr><td valign="top"> {@code 'E'}1201* <td valign="top"> <tt>'\u0045'</tt>1202* <td> The upper-case variant of {@code 'e'}. The exponent symbol1203* will be {@code 'E'} (<tt>'\u0045'</tt>).1204*1205* <tr><td valign="top"> {@code 'g'}1206* <td valign="top"> <tt>'\u0067'</tt>1207* <td> Requires the output to be formatted in general scientific notation1208* as described below. The <a href="#L10nAlgorithm">localization1209* algorithm</a> is applied.1210*1211* <p> After rounding for the precision, the formatting of the resulting1212* magnitude <i>m</i> depends on its value.1213*1214* <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less1215* than 10<sup>precision</sup> then it is represented in <i><a1216* href="#decimal">decimal format</a></i>.1217*1218* <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to1219* 10<sup>precision</sup>, then it is represented in <i><a1220* href="#scientific">computerized scientific notation</a></i>.1221*1222* <p> The total number of significant digits in <i>m</i> is equal to the1223* precision. If the precision is not specified, then the default value is1224* {@code 6}. If the precision is {@code 0}, then it is taken to be1225* {@code 1}.1226*1227* <p> If the {@code '#'} flag is given then an {@link1228* FormatFlagsConversionMismatchException} will be thrown.1229*1230* <tr><td valign="top"> {@code 'G'}1231* <td valign="top"> <tt>'\u0047'</tt>1232* <td> The upper-case variant of {@code 'g'}.1233*1234* <tr><td valign="top"> {@code 'f'}1235* <td valign="top"> <tt>'\u0066'</tt>1236* <td> Requires the output to be formatted using <a name="decimal">decimal1237* format</a>. The <a href="#L10nAlgorithm">localization algorithm</a> is1238* applied.1239*1240* <p> The result is a string that represents the sign and magnitude1241* (absolute value) of the argument. The formatting of the sign is1242* described in the <a href="#L10nAlgorithm">localization1243* algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its1244* value.1245*1246* <p> If <i>m</i> NaN or infinite, the literal strings "NaN" or1247* "Infinity", respectively, will be output. These values are not1248* localized.1249*1250* <p> The magnitude is formatted as the integer part of <i>m</i>, with no1251* leading zeroes, followed by the decimal separator followed by one or1252* more decimal digits representing the fractional part of <i>m</i>.1253*1254* <p> The number of digits in the result for the fractional part of1255* <i>m</i> or <i>a</i> is equal to the precision. If the precision is not1256* specified then the default value is {@code 6}. If the precision is less1257* than the number of digits which would appear after the decimal point in1258* the string returned by {@link Float#toString(float)} or {@link1259* Double#toString(double)} respectively, then the value will be rounded1260* using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up1261* algorithm}. Otherwise, zeros may be appended to reach the precision.1262* For a canonical representation of the value, use {@link1263* Float#toString(float)} or {@link Double#toString(double)} as1264* appropriate.1265*1266* <tr><td valign="top"> {@code 'a'}1267* <td valign="top"> <tt>'\u0061'</tt>1268* <td> Requires the output to be formatted in hexadecimal exponential1269* form. No localization is applied.1270*1271* <p> The result is a string that represents the sign and magnitude1272* (absolute value) of the argument <i>x</i>.1273*1274* <p> If <i>x</i> is negative or a negative-zero value then the result1275* will begin with {@code '-'} (<tt>'\u002d'</tt>).1276*1277* <p> If <i>x</i> is positive or a positive-zero value and the1278* {@code '+'} flag is given then the result will begin with {@code '+'}1279* (<tt>'\u002b'</tt>).1280*1281* <p> The formatting of the magnitude <i>m</i> depends upon its value.1282*1283* <ul>1284*1285* <li> If the value is NaN or infinite, the literal strings "NaN" or1286* "Infinity", respectively, will be output.1287*1288* <li> If <i>m</i> is zero then it is represented by the string1289* {@code "0x0.0p0"}.1290*1291* <li> If <i>m</i> is a {@code double} value with a normalized1292* representation then substrings are used to represent the significand and1293* exponent fields. The significand is represented by the characters1294* {@code "0x1."} followed by the hexadecimal representation of the rest1295* of the significand as a fraction. The exponent is represented by1296* {@code 'p'} (<tt>'\u0070'</tt>) followed by a decimal string of the1297* unbiased exponent as if produced by invoking {@link1298* Integer#toString(int) Integer.toString} on the exponent value. If the1299* precision is specified, the value is rounded to the given number of1300* hexadecimal digits.1301*1302* <li> If <i>m</i> is a {@code double} value with a subnormal1303* representation then, unless the precision is specified to be in the range1304* 1 through 12, inclusive, the significand is represented by the characters1305* {@code '0x0.'} followed by the hexadecimal representation of the rest of1306* the significand as a fraction, and the exponent represented by1307* {@code 'p-1022'}. If the precision is in the interval1308* [1, 12], the subnormal value is normalized such that it1309* begins with the characters {@code '0x1.'}, rounded to the number of1310* hexadecimal digits of precision, and the exponent adjusted1311* accordingly. Note that there must be at least one nonzero digit in a1312* subnormal significand.1313*1314* </ul>1315*1316* <p> If the {@code '('} or {@code ','} flags are given, then a {@link1317* FormatFlagsConversionMismatchException} will be thrown.1318*1319* <tr><td valign="top"> {@code 'A'}1320* <td valign="top"> <tt>'\u0041'</tt>1321* <td> The upper-case variant of {@code 'a'}. The entire string1322* representing the number will be converted to upper case including the1323* {@code 'x'} (<tt>'\u0078'</tt>) and {@code 'p'}1324* (<tt>'\u0070'</tt> and all hexadecimal digits {@code 'a'} -1325* {@code 'f'} (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>).1326*1327* </table>1328*1329* <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and1330* Long apply.1331*1332* <p> If the {@code '#'} flag is given, then the decimal separator will1333* always be present.1334*1335* <p> If no <a name="floatdFlags">flags</a> are given the default formatting1336* is as follows:1337*1338* <ul>1339*1340* <li> The output is right-justified within the {@code width}1341*1342* <li> Negative numbers begin with a {@code '-'}1343*1344* <li> Positive numbers and positive zero do not include a sign or extra1345* leading space1346*1347* <li> No grouping separators are included1348*1349* <li> The decimal separator will only appear if a digit follows it1350*1351* </ul>1352*1353* <p> The <a name="floatDWidth">width</a> is the minimum number of characters1354* to be written to the output. This includes any signs, digits, grouping1355* separators, decimal separators, exponential symbol, radix indicator,1356* parentheses, and strings representing infinity and NaN as applicable. If1357* the length of the converted value is less than the width then the output1358* will be padded by spaces (<tt>'\u0020'</tt>) until the total number of1359* characters equals width. The padding is on the left by default. If the1360* {@code '-'} flag is given then the padding will be on the right. If width1361* is not specified then there is no minimum.1362*1363* <p> If the <a name="floatDPrec">conversion</a> is {@code 'e'},1364* {@code 'E'} or {@code 'f'}, then the precision is the number of digits1365* after the decimal separator. If the precision is not specified, then it is1366* assumed to be {@code 6}.1367*1368* <p> If the conversion is {@code 'g'} or {@code 'G'}, then the precision is1369* the total number of significant digits in the resulting magnitude after1370* rounding. If the precision is not specified, then the default value is1371* {@code 6}. If the precision is {@code 0}, then it is taken to be1372* {@code 1}.1373*1374* <p> If the conversion is {@code 'a'} or {@code 'A'}, then the precision1375* is the number of hexadecimal digits after the radix point. If the1376* precision is not provided, then all of the digits as returned by {@link1377* Double#toHexString(double)} will be output.1378*1379* <p><a name="dnbdec"><b> BigDecimal </b></a>1380*1381* <p> The following conversions may be applied {@link java.math.BigDecimal1382* BigDecimal}.1383*1384* <table cellpadding=5 summary="floatConv">1385*1386* <tr><td valign="top"> {@code 'e'}1387* <td valign="top"> <tt>'\u0065'</tt>1388* <td> Requires the output to be formatted using <a1389* name="bscientific">computerized scientific notation</a>. The <a1390* href="#L10nAlgorithm">localization algorithm</a> is applied.1391*1392* <p> The formatting of the magnitude <i>m</i> depends upon its value.1393*1394* <p> If <i>m</i> is positive-zero or negative-zero, then the exponent1395* will be {@code "+00"}.1396*1397* <p> Otherwise, the result is a string that represents the sign and1398* magnitude (absolute value) of the argument. The formatting of the sign1399* is described in the <a href="#L10nAlgorithm">localization1400* algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its1401* value.1402*1403* <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup>1404* <= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the1405* mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so1406* that 1 <= <i>a</i> < 10. The magnitude is then represented as the1407* integer part of <i>a</i>, as a single decimal digit, followed by the1408* decimal separator followed by decimal digits representing the fractional1409* part of <i>a</i>, followed by the exponent symbol {@code 'e'}1410* (<tt>'\u0065'</tt>), followed by the sign of the exponent, followed1411* by a representation of <i>n</i> as a decimal integer, as produced by the1412* method {@link Long#toString(long, int)}, and zero-padded to include at1413* least two digits.1414*1415* <p> The number of digits in the result for the fractional part of1416* <i>m</i> or <i>a</i> is equal to the precision. If the precision is not1417* specified then the default value is {@code 6}. If the precision is1418* less than the number of digits to the right of the decimal point then1419* the value will be rounded using the1420* {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up1421* algorithm}. Otherwise, zeros may be appended to reach the precision.1422* For a canonical representation of the value, use {@link1423* BigDecimal#toString()}.1424*1425* <p> If the {@code ','} flag is given, then an {@link1426* FormatFlagsConversionMismatchException} will be thrown.1427*1428* <tr><td valign="top"> {@code 'E'}1429* <td valign="top"> <tt>'\u0045'</tt>1430* <td> The upper-case variant of {@code 'e'}. The exponent symbol1431* will be {@code 'E'} (<tt>'\u0045'</tt>).1432*1433* <tr><td valign="top"> {@code 'g'}1434* <td valign="top"> <tt>'\u0067'</tt>1435* <td> Requires the output to be formatted in general scientific notation1436* as described below. The <a href="#L10nAlgorithm">localization1437* algorithm</a> is applied.1438*1439* <p> After rounding for the precision, the formatting of the resulting1440* magnitude <i>m</i> depends on its value.1441*1442* <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less1443* than 10<sup>precision</sup> then it is represented in <i><a1444* href="#bdecimal">decimal format</a></i>.1445*1446* <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to1447* 10<sup>precision</sup>, then it is represented in <i><a1448* href="#bscientific">computerized scientific notation</a></i>.1449*1450* <p> The total number of significant digits in <i>m</i> is equal to the1451* precision. If the precision is not specified, then the default value is1452* {@code 6}. If the precision is {@code 0}, then it is taken to be1453* {@code 1}.1454*1455* <p> If the {@code '#'} flag is given then an {@link1456* FormatFlagsConversionMismatchException} will be thrown.1457*1458* <tr><td valign="top"> {@code 'G'}1459* <td valign="top"> <tt>'\u0047'</tt>1460* <td> The upper-case variant of {@code 'g'}.1461*1462* <tr><td valign="top"> {@code 'f'}1463* <td valign="top"> <tt>'\u0066'</tt>1464* <td> Requires the output to be formatted using <a name="bdecimal">decimal1465* format</a>. The <a href="#L10nAlgorithm">localization algorithm</a> is1466* applied.1467*1468* <p> The result is a string that represents the sign and magnitude1469* (absolute value) of the argument. The formatting of the sign is1470* described in the <a href="#L10nAlgorithm">localization1471* algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its1472* value.1473*1474* <p> The magnitude is formatted as the integer part of <i>m</i>, with no1475* leading zeroes, followed by the decimal separator followed by one or1476* more decimal digits representing the fractional part of <i>m</i>.1477*1478* <p> The number of digits in the result for the fractional part of1479* <i>m</i> or <i>a</i> is equal to the precision. If the precision is not1480* specified then the default value is {@code 6}. If the precision is1481* less than the number of digits to the right of the decimal point1482* then the value will be rounded using the1483* {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up1484* algorithm}. Otherwise, zeros may be appended to reach the precision.1485* For a canonical representation of the value, use {@link1486* BigDecimal#toString()}.1487*1488* </table>1489*1490* <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and1491* Long apply.1492*1493* <p> If the {@code '#'} flag is given, then the decimal separator will1494* always be present.1495*1496* <p> The <a href="#floatdFlags">default behavior</a> when no flags are1497* given is the same as for Float and Double.1498*1499* <p> The specification of <a href="#floatDWidth">width</a> and <a1500* href="#floatDPrec">precision</a> is the same as defined for Float and1501* Double.1502*1503* <h4><a name="ddt">Date/Time</a></h4>1504*1505* <p> This conversion may be applied to {@code long}, {@link Long}, {@link1506* Calendar}, {@link Date} and {@link TemporalAccessor TemporalAccessor}1507*1508* <table cellpadding=5 summary="DTConv">1509*1510* <tr><td valign="top"> {@code 't'}1511* <td valign="top"> <tt>'\u0074'</tt>1512* <td> Prefix for date and time conversion characters.1513* <tr><td valign="top"> {@code 'T'}1514* <td valign="top"> <tt>'\u0054'</tt>1515* <td> The upper-case variant of {@code 't'}.1516*1517* </table>1518*1519* <p> The following date and time conversion character suffixes are defined1520* for the {@code 't'} and {@code 'T'} conversions. The types are similar to1521* but not completely identical to those defined by GNU {@code date} and1522* POSIX {@code strftime(3c)}. Additional conversion types are provided to1523* access Java-specific functionality (e.g. {@code 'L'} for milliseconds1524* within the second).1525*1526* <p> The following conversion characters are used for formatting times:1527*1528* <table cellpadding=5 summary="time">1529*1530* <tr><td valign="top"> {@code 'H'}1531* <td valign="top"> <tt>'\u0048'</tt>1532* <td> Hour of the day for the 24-hour clock, formatted as two digits with1533* a leading zero as necessary i.e. {@code 00 - 23}. {@code 00}1534* corresponds to midnight.1535*1536* <tr><td valign="top">{@code 'I'}1537* <td valign="top"> <tt>'\u0049'</tt>1538* <td> Hour for the 12-hour clock, formatted as two digits with a leading1539* zero as necessary, i.e. {@code 01 - 12}. {@code 01} corresponds to1540* one o'clock (either morning or afternoon).1541*1542* <tr><td valign="top">{@code 'k'}1543* <td valign="top"> <tt>'\u006b'</tt>1544* <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}.1545* {@code 0} corresponds to midnight.1546*1547* <tr><td valign="top">{@code 'l'}1548* <td valign="top"> <tt>'\u006c'</tt>1549* <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}. {@code 1}1550* corresponds to one o'clock (either morning or afternoon).1551*1552* <tr><td valign="top">{@code 'M'}1553* <td valign="top"> <tt>'\u004d'</tt>1554* <td> Minute within the hour formatted as two digits with a leading zero1555* as necessary, i.e. {@code 00 - 59}.1556*1557* <tr><td valign="top">{@code 'S'}1558* <td valign="top"> <tt>'\u0053'</tt>1559* <td> Seconds within the minute, formatted as two digits with a leading1560* zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special1561* value required to support leap seconds).1562*1563* <tr><td valign="top">{@code 'L'}1564* <td valign="top"> <tt>'\u004c'</tt>1565* <td> Millisecond within the second formatted as three digits with1566* leading zeros as necessary, i.e. {@code 000 - 999}.1567*1568* <tr><td valign="top">{@code 'N'}1569* <td valign="top"> <tt>'\u004e'</tt>1570* <td> Nanosecond within the second, formatted as nine digits with leading1571* zeros as necessary, i.e. {@code 000000000 - 999999999}. The precision1572* of this value is limited by the resolution of the underlying operating1573* system or hardware.1574*1575* <tr><td valign="top">{@code 'p'}1576* <td valign="top"> <tt>'\u0070'</tt>1577* <td> Locale-specific {@linkplain1578* java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker1579* in lower case, e.g."{@code am}" or "{@code pm}". Use of the1580* conversion prefix {@code 'T'} forces this output to upper case. (Note1581* that {@code 'p'} produces lower-case output. This is different from1582* GNU {@code date} and POSIX {@code strftime(3c)} which produce1583* upper-case output.)1584*1585* <tr><td valign="top">{@code 'z'}1586* <td valign="top"> <tt>'\u007a'</tt>1587* <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a>1588* style numeric time zone offset from GMT, e.g. {@code -0800}. This1589* value will be adjusted as necessary for Daylight Saving Time. For1590* {@code long}, {@link Long}, and {@link Date} the time zone used is1591* the {@linkplain TimeZone#getDefault() default time zone} for this1592* instance of the Java virtual machine.1593*1594* <tr><td valign="top">{@code 'Z'}1595* <td valign="top"> <tt>'\u005a'</tt>1596* <td> A string representing the abbreviation for the time zone. This1597* value will be adjusted as necessary for Daylight Saving Time. For1598* {@code long}, {@link Long}, and {@link Date} the time zone used is1599* the {@linkplain TimeZone#getDefault() default time zone} for this1600* instance of the Java virtual machine. The Formatter's locale will1601* supersede the locale of the argument (if any).1602*1603* <tr><td valign="top">{@code 's'}1604* <td valign="top"> <tt>'\u0073'</tt>1605* <td> Seconds since the beginning of the epoch starting at 1 January 19701606* {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to1607* {@code Long.MAX_VALUE/1000}.1608*1609* <tr><td valign="top">{@code 'Q'}1610* <td valign="top"> <tt>'\u004f'</tt>1611* <td> Milliseconds since the beginning of the epoch starting at 1 January1612* 1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to1613* {@code Long.MAX_VALUE}. The precision of this value is limited by1614* the resolution of the underlying operating system or hardware.1615*1616* </table>1617*1618* <p> The following conversion characters are used for formatting dates:1619*1620* <table cellpadding=5 summary="date">1621*1622* <tr><td valign="top">{@code 'B'}1623* <td valign="top"> <tt>'\u0042'</tt>1624* <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths1625* full month name}, e.g. {@code "January"}, {@code "February"}.1626*1627* <tr><td valign="top">{@code 'b'}1628* <td valign="top"> <tt>'\u0062'</tt>1629* <td> Locale-specific {@linkplain1630* java.text.DateFormatSymbols#getShortMonths abbreviated month name},1631* e.g. {@code "Jan"}, {@code "Feb"}.1632*1633* <tr><td valign="top">{@code 'h'}1634* <td valign="top"> <tt>'\u0068'</tt>1635* <td> Same as {@code 'b'}.1636*1637* <tr><td valign="top">{@code 'A'}1638* <td valign="top"> <tt>'\u0041'</tt>1639* <td> Locale-specific full name of the {@linkplain1640* java.text.DateFormatSymbols#getWeekdays day of the week},1641* e.g. {@code "Sunday"}, {@code "Monday"}1642*1643* <tr><td valign="top">{@code 'a'}1644* <td valign="top"> <tt>'\u0061'</tt>1645* <td> Locale-specific short name of the {@linkplain1646* java.text.DateFormatSymbols#getShortWeekdays day of the week},1647* e.g. {@code "Sun"}, {@code "Mon"}1648*1649* <tr><td valign="top">{@code 'C'}1650* <td valign="top"> <tt>'\u0043'</tt>1651* <td> Four-digit year divided by {@code 100}, formatted as two digits1652* with leading zero as necessary, i.e. {@code 00 - 99}1653*1654* <tr><td valign="top">{@code 'Y'}1655* <td valign="top"> <tt>'\u0059'</tt> <td> Year, formatted to at least1656* four digits with leading zeros as necessary, e.g. {@code 0092} equals1657* {@code 92} CE for the Gregorian calendar.1658*1659* <tr><td valign="top">{@code 'y'}1660* <td valign="top"> <tt>'\u0079'</tt>1661* <td> Last two digits of the year, formatted with leading zeros as1662* necessary, i.e. {@code 00 - 99}.1663*1664* <tr><td valign="top">{@code 'j'}1665* <td valign="top"> <tt>'\u006a'</tt>1666* <td> Day of year, formatted as three digits with leading zeros as1667* necessary, e.g. {@code 001 - 366} for the Gregorian calendar.1668* {@code 001} corresponds to the first day of the year.1669*1670* <tr><td valign="top">{@code 'm'}1671* <td valign="top"> <tt>'\u006d'</tt>1672* <td> Month, formatted as two digits with leading zeros as necessary,1673* i.e. {@code 01 - 13}, where "{@code 01}" is the first month of the1674* year and ("{@code 13}" is a special value required to support lunar1675* calendars).1676*1677* <tr><td valign="top">{@code 'd'}1678* <td valign="top"> <tt>'\u0064'</tt>1679* <td> Day of month, formatted as two digits with leading zeros as1680* necessary, i.e. {@code 01 - 31}, where "{@code 01}" is the first day1681* of the month.1682*1683* <tr><td valign="top">{@code 'e'}1684* <td valign="top"> <tt>'\u0065'</tt>1685* <td> Day of month, formatted as two digits, i.e. {@code 1 - 31} where1686* "{@code 1}" is the first day of the month.1687*1688* </table>1689*1690* <p> The following conversion characters are used for formatting common1691* date/time compositions.1692*1693* <table cellpadding=5 summary="composites">1694*1695* <tr><td valign="top">{@code 'R'}1696* <td valign="top"> <tt>'\u0052'</tt>1697* <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"}1698*1699* <tr><td valign="top">{@code 'T'}1700* <td valign="top"> <tt>'\u0054'</tt>1701* <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}.1702*1703* <tr><td valign="top">{@code 'r'}1704* <td valign="top"> <tt>'\u0072'</tt>1705* <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS1706* %Tp"}. The location of the morning or afternoon marker1707* ({@code '%Tp'}) may be locale-dependent.1708*1709* <tr><td valign="top">{@code 'D'}1710* <td valign="top"> <tt>'\u0044'</tt>1711* <td> Date formatted as {@code "%tm/%td/%ty"}.1712*1713* <tr><td valign="top">{@code 'F'}1714* <td valign="top"> <tt>'\u0046'</tt>1715* <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a>1716* complete date formatted as {@code "%tY-%tm-%td"}.1717*1718* <tr><td valign="top">{@code 'c'}1719* <td valign="top"> <tt>'\u0063'</tt>1720* <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"},1721* e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}.1722*1723* </table>1724*1725* <p> The {@code '-'} flag defined for <a href="#dFlags">General1726* conversions</a> applies. If the {@code '#'} flag is given, then a {@link1727* FormatFlagsConversionMismatchException} will be thrown.1728*1729* <p> The width is the minimum number of characters to1730* be written to the output. If the length of the converted value is less than1731* the {@code width} then the output will be padded by spaces1732* (<tt>'\u0020'</tt>) until the total number of characters equals width.1733* The padding is on the left by default. If the {@code '-'} flag is given1734* then the padding will be on the right. If width is not specified then there1735* is no minimum.1736*1737* <p> The precision is not applicable. If the precision is specified then an1738* {@link IllegalFormatPrecisionException} will be thrown.1739*1740* <h4><a name="dper">Percent</a></h4>1741*1742* <p> The conversion does not correspond to any argument.1743*1744* <table cellpadding=5 summary="DTConv">1745*1746* <tr><td valign="top">{@code '%'}1747* <td> The result is a literal {@code '%'} (<tt>'\u0025'</tt>)1748*1749* <p> The width is the minimum number of characters to1750* be written to the output including the {@code '%'}. If the length of the1751* converted value is less than the {@code width} then the output will be1752* padded by spaces (<tt>'\u0020'</tt>) until the total number of1753* characters equals width. The padding is on the left. If width is not1754* specified then just the {@code '%'} is output.1755*1756* <p> The {@code '-'} flag defined for <a href="#dFlags">General1757* conversions</a> applies. If any other flags are provided, then a1758* {@link FormatFlagsConversionMismatchException} will be thrown.1759*1760* <p> The precision is not applicable. If the precision is specified an1761* {@link IllegalFormatPrecisionException} will be thrown.1762*1763* </table>1764*1765* <h4><a name="dls">Line Separator</a></h4>1766*1767* <p> The conversion does not correspond to any argument.1768*1769* <table cellpadding=5 summary="DTConv">1770*1771* <tr><td valign="top">{@code 'n'}1772* <td> the platform-specific line separator as returned by {@link1773* System#getProperty System.getProperty("line.separator")}.1774*1775* </table>1776*1777* <p> Flags, width, and precision are not applicable. If any are provided an1778* {@link IllegalFormatFlagsException}, {@link IllegalFormatWidthException},1779* and {@link IllegalFormatPrecisionException}, respectively will be thrown.1780*1781* <h4><a name="dpos">Argument Index</a></h4>1782*1783* <p> Format specifiers can reference arguments in three ways:1784*1785* <ul>1786*1787* <li> <i>Explicit indexing</i> is used when the format specifier contains an1788* argument index. The argument index is a decimal integer indicating the1789* position of the argument in the argument list. The first argument is1790* referenced by "{@code 1$}", the second by "{@code 2$}", etc. An argument1791* may be referenced more than once.1792*1793* <p> For example:1794*1795* <blockquote><pre>1796* formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",1797* "a", "b", "c", "d")1798* // -> "d c b a d c b a"1799* </pre></blockquote>1800*1801* <li> <i>Relative indexing</i> is used when the format specifier contains a1802* {@code '<'} (<tt>'\u003c'</tt>) flag which causes the argument for1803* the previous format specifier to be re-used. If there is no previous1804* argument, then a {@link MissingFormatArgumentException} is thrown.1805*1806* <blockquote><pre>1807* formatter.format("%s %s %<s %<s", "a", "b", "c", "d")1808* // -> "a b b b"1809* // "c" and "d" are ignored because they are not referenced1810* </pre></blockquote>1811*1812* <li> <i>Ordinary indexing</i> is used when the format specifier contains1813* neither an argument index nor a {@code '<'} flag. Each format specifier1814* which uses ordinary indexing is assigned a sequential implicit index into1815* argument list which is independent of the indices used by explicit or1816* relative indexing.1817*1818* <blockquote><pre>1819* formatter.format("%s %s %s %s", "a", "b", "c", "d")1820* // -> "a b c d"1821* </pre></blockquote>1822*1823* </ul>1824*1825* <p> It is possible to have a format string which uses all forms of indexing,1826* for example:1827*1828* <blockquote><pre>1829* formatter.format("%2$s %s %<s %s", "a", "b", "c", "d")1830* // -> "b a a b"1831* // "c" and "d" are ignored because they are not referenced1832* </pre></blockquote>1833*1834* <p> The maximum number of arguments is limited by the maximum dimension of a1835* Java array as defined by1836* <cite>The Java™ Virtual Machine Specification</cite>.1837* If the argument index is does not correspond to an1838* available argument, then a {@link MissingFormatArgumentException} is thrown.1839*1840* <p> If there are more arguments than format specifiers, the extra arguments1841* are ignored.1842*1843* <p> Unless otherwise specified, passing a {@code null} argument to any1844* method or constructor in this class will cause a {@link1845* NullPointerException} to be thrown.1846*1847* @author Iris Clark1848* @since 1.51849*/1850public final class Formatter implements Closeable, Flushable {1851private Appendable a;1852private final Locale l;18531854private IOException lastException;18551856private final char zero;1857private static double scaleUp;18581859// 1 (sign) + 19 (max # sig digits) + 1 ('.') + 1 ('e') + 1 (sign)1860// + 3 (max # exp digits) + 4 (error) = 301861private static final int MAX_FD_CHARS = 30;18621863/**1864* Returns a charset object for the given charset name.1865* @throws NullPointerException is csn is null1866* @throws UnsupportedEncodingException if the charset is not supported1867*/1868private static Charset toCharset(String csn)1869throws UnsupportedEncodingException1870{1871Objects.requireNonNull(csn, "charsetName");1872try {1873return Charset.forName(csn);1874} catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {1875// UnsupportedEncodingException should be thrown1876throw new UnsupportedEncodingException(csn);1877}1878}18791880private static final Appendable nonNullAppendable(Appendable a) {1881if (a == null)1882return new StringBuilder();18831884return a;1885}18861887/* Private constructors */1888private Formatter(Locale l, Appendable a) {1889this.a = a;1890this.l = l;1891this.zero = getZero(l);1892}18931894private Formatter(Charset charset, Locale l, File file)1895throws FileNotFoundException1896{1897this(l,1898new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)));1899}19001901/**1902* Constructs a new formatter.1903*1904* <p> The destination of the formatted output is a {@link StringBuilder}1905* which may be retrieved by invoking {@link #out out()} and whose1906* current content may be converted into a string by invoking {@link1907* #toString toString()}. The locale used is the {@linkplain1908* Locale#getDefault(Locale.Category) default locale} for1909* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java1910* virtual machine.1911*/1912public Formatter() {1913this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder());1914}19151916/**1917* Constructs a new formatter with the specified destination.1918*1919* <p> The locale used is the {@linkplain1920* Locale#getDefault(Locale.Category) default locale} for1921* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java1922* virtual machine.1923*1924* @param a1925* Destination for the formatted output. If {@code a} is1926* {@code null} then a {@link StringBuilder} will be created.1927*/1928public Formatter(Appendable a) {1929this(Locale.getDefault(Locale.Category.FORMAT), nonNullAppendable(a));1930}19311932/**1933* Constructs a new formatter with the specified locale.1934*1935* <p> The destination of the formatted output is a {@link StringBuilder}1936* which may be retrieved by invoking {@link #out out()} and whose current1937* content may be converted into a string by invoking {@link #toString1938* toString()}.1939*1940* @param l1941* The {@linkplain java.util.Locale locale} to apply during1942* formatting. If {@code l} is {@code null} then no localization1943* is applied.1944*/1945public Formatter(Locale l) {1946this(l, new StringBuilder());1947}19481949/**1950* Constructs a new formatter with the specified destination and locale.1951*1952* @param a1953* Destination for the formatted output. If {@code a} is1954* {@code null} then a {@link StringBuilder} will be created.1955*1956* @param l1957* The {@linkplain java.util.Locale locale} to apply during1958* formatting. If {@code l} is {@code null} then no localization1959* is applied.1960*/1961public Formatter(Appendable a, Locale l) {1962this(l, nonNullAppendable(a));1963}19641965/**1966* Constructs a new formatter with the specified file name.1967*1968* <p> The charset used is the {@linkplain1969* java.nio.charset.Charset#defaultCharset() default charset} for this1970* instance of the Java virtual machine.1971*1972* <p> The locale used is the {@linkplain1973* Locale#getDefault(Locale.Category) default locale} for1974* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java1975* virtual machine.1976*1977* @param fileName1978* The name of the file to use as the destination of this1979* formatter. If the file exists then it will be truncated to1980* zero size; otherwise, a new file will be created. The output1981* will be written to the file and is buffered.1982*1983* @throws SecurityException1984* If a security manager is present and {@link1985* SecurityManager#checkWrite checkWrite(fileName)} denies write1986* access to the file1987*1988* @throws FileNotFoundException1989* If the given file name does not denote an existing, writable1990* regular file and a new regular file of that name cannot be1991* created, or if some other error occurs while opening or1992* creating the file1993*/1994public Formatter(String fileName) throws FileNotFoundException {1995this(Locale.getDefault(Locale.Category.FORMAT),1996new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))));1997}19981999/**2000* Constructs a new formatter with the specified file name and charset.2001*2002* <p> The locale used is the {@linkplain2003* Locale#getDefault(Locale.Category) default locale} for2004* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2005* virtual machine.2006*2007* @param fileName2008* The name of the file to use as the destination of this2009* formatter. If the file exists then it will be truncated to2010* zero size; otherwise, a new file will be created. The output2011* will be written to the file and is buffered.2012*2013* @param csn2014* The name of a supported {@linkplain java.nio.charset.Charset2015* charset}2016*2017* @throws FileNotFoundException2018* If the given file name does not denote an existing, writable2019* regular file and a new regular file of that name cannot be2020* created, or if some other error occurs while opening or2021* creating the file2022*2023* @throws SecurityException2024* If a security manager is present and {@link2025* SecurityManager#checkWrite checkWrite(fileName)} denies write2026* access to the file2027*2028* @throws UnsupportedEncodingException2029* If the named charset is not supported2030*/2031public Formatter(String fileName, String csn)2032throws FileNotFoundException, UnsupportedEncodingException2033{2034this(fileName, csn, Locale.getDefault(Locale.Category.FORMAT));2035}20362037/**2038* Constructs a new formatter with the specified file name, charset, and2039* locale.2040*2041* @param fileName2042* The name of the file to use as the destination of this2043* formatter. If the file exists then it will be truncated to2044* zero size; otherwise, a new file will be created. The output2045* will be written to the file and is buffered.2046*2047* @param csn2048* The name of a supported {@linkplain java.nio.charset.Charset2049* charset}2050*2051* @param l2052* The {@linkplain java.util.Locale locale} to apply during2053* formatting. If {@code l} is {@code null} then no localization2054* is applied.2055*2056* @throws FileNotFoundException2057* If the given file name does not denote an existing, writable2058* regular file and a new regular file of that name cannot be2059* created, or if some other error occurs while opening or2060* creating the file2061*2062* @throws SecurityException2063* If a security manager is present and {@link2064* SecurityManager#checkWrite checkWrite(fileName)} denies write2065* access to the file2066*2067* @throws UnsupportedEncodingException2068* If the named charset is not supported2069*/2070public Formatter(String fileName, String csn, Locale l)2071throws FileNotFoundException, UnsupportedEncodingException2072{2073this(toCharset(csn), l, new File(fileName));2074}20752076/**2077* Constructs a new formatter with the specified file.2078*2079* <p> The charset used is the {@linkplain2080* java.nio.charset.Charset#defaultCharset() default charset} for this2081* instance of the Java virtual machine.2082*2083* <p> The locale used is the {@linkplain2084* Locale#getDefault(Locale.Category) default locale} for2085* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2086* virtual machine.2087*2088* @param file2089* The file to use as the destination of this formatter. If the2090* file exists then it will be truncated to zero size; otherwise,2091* a new file will be created. The output will be written to the2092* file and is buffered.2093*2094* @throws SecurityException2095* If a security manager is present and {@link2096* SecurityManager#checkWrite checkWrite(file.getPath())} denies2097* write access to the file2098*2099* @throws FileNotFoundException2100* If the given file object does not denote an existing, writable2101* regular file and a new regular file of that name cannot be2102* created, or if some other error occurs while opening or2103* creating the file2104*/2105public Formatter(File file) throws FileNotFoundException {2106this(Locale.getDefault(Locale.Category.FORMAT),2107new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))));2108}21092110/**2111* Constructs a new formatter with the specified file and charset.2112*2113* <p> The locale used is the {@linkplain2114* Locale#getDefault(Locale.Category) default locale} for2115* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2116* virtual machine.2117*2118* @param file2119* The file to use as the destination of this formatter. If the2120* file exists then it will be truncated to zero size; otherwise,2121* a new file will be created. The output will be written to the2122* file and is buffered.2123*2124* @param csn2125* The name of a supported {@linkplain java.nio.charset.Charset2126* charset}2127*2128* @throws FileNotFoundException2129* If the given file object does not denote an existing, writable2130* regular file and a new regular file of that name cannot be2131* created, or if some other error occurs while opening or2132* creating the file2133*2134* @throws SecurityException2135* If a security manager is present and {@link2136* SecurityManager#checkWrite checkWrite(file.getPath())} denies2137* write access to the file2138*2139* @throws UnsupportedEncodingException2140* If the named charset is not supported2141*/2142public Formatter(File file, String csn)2143throws FileNotFoundException, UnsupportedEncodingException2144{2145this(file, csn, Locale.getDefault(Locale.Category.FORMAT));2146}21472148/**2149* Constructs a new formatter with the specified file, charset, and2150* locale.2151*2152* @param file2153* The file to use as the destination of this formatter. If the2154* file exists then it will be truncated to zero size; otherwise,2155* a new file will be created. The output will be written to the2156* file and is buffered.2157*2158* @param csn2159* The name of a supported {@linkplain java.nio.charset.Charset2160* charset}2161*2162* @param l2163* The {@linkplain java.util.Locale locale} to apply during2164* formatting. If {@code l} is {@code null} then no localization2165* is applied.2166*2167* @throws FileNotFoundException2168* If the given file object does not denote an existing, writable2169* regular file and a new regular file of that name cannot be2170* created, or if some other error occurs while opening or2171* creating the file2172*2173* @throws SecurityException2174* If a security manager is present and {@link2175* SecurityManager#checkWrite checkWrite(file.getPath())} denies2176* write access to the file2177*2178* @throws UnsupportedEncodingException2179* If the named charset is not supported2180*/2181public Formatter(File file, String csn, Locale l)2182throws FileNotFoundException, UnsupportedEncodingException2183{2184this(toCharset(csn), l, file);2185}21862187/**2188* Constructs a new formatter with the specified print stream.2189*2190* <p> The locale used is the {@linkplain2191* Locale#getDefault(Locale.Category) default locale} for2192* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2193* virtual machine.2194*2195* <p> Characters are written to the given {@link java.io.PrintStream2196* PrintStream} object and are therefore encoded using that object's2197* charset.2198*2199* @param ps2200* The stream to use as the destination of this formatter.2201*/2202public Formatter(PrintStream ps) {2203this(Locale.getDefault(Locale.Category.FORMAT),2204(Appendable)Objects.requireNonNull(ps));2205}22062207/**2208* Constructs a new formatter with the specified output stream.2209*2210* <p> The charset used is the {@linkplain2211* java.nio.charset.Charset#defaultCharset() default charset} for this2212* instance of the Java virtual machine.2213*2214* <p> The locale used is the {@linkplain2215* Locale#getDefault(Locale.Category) default locale} for2216* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2217* virtual machine.2218*2219* @param os2220* The output stream to use as the destination of this formatter.2221* The output will be buffered.2222*/2223public Formatter(OutputStream os) {2224this(Locale.getDefault(Locale.Category.FORMAT),2225new BufferedWriter(new OutputStreamWriter(os)));2226}22272228/**2229* Constructs a new formatter with the specified output stream and2230* charset.2231*2232* <p> The locale used is the {@linkplain2233* Locale#getDefault(Locale.Category) default locale} for2234* {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java2235* virtual machine.2236*2237* @param os2238* The output stream to use as the destination of this formatter.2239* The output will be buffered.2240*2241* @param csn2242* The name of a supported {@linkplain java.nio.charset.Charset2243* charset}2244*2245* @throws UnsupportedEncodingException2246* If the named charset is not supported2247*/2248public Formatter(OutputStream os, String csn)2249throws UnsupportedEncodingException2250{2251this(os, csn, Locale.getDefault(Locale.Category.FORMAT));2252}22532254/**2255* Constructs a new formatter with the specified output stream, charset,2256* and locale.2257*2258* @param os2259* The output stream to use as the destination of this formatter.2260* The output will be buffered.2261*2262* @param csn2263* The name of a supported {@linkplain java.nio.charset.Charset2264* charset}2265*2266* @param l2267* The {@linkplain java.util.Locale locale} to apply during2268* formatting. If {@code l} is {@code null} then no localization2269* is applied.2270*2271* @throws UnsupportedEncodingException2272* If the named charset is not supported2273*/2274public Formatter(OutputStream os, String csn, Locale l)2275throws UnsupportedEncodingException2276{2277this(l, new BufferedWriter(new OutputStreamWriter(os, csn)));2278}22792280private static char getZero(Locale l) {2281if ((l != null) && !l.equals(Locale.US)) {2282DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);2283return dfs.getZeroDigit();2284} else {2285return '0';2286}2287}22882289/**2290* Returns the locale set by the construction of this formatter.2291*2292* <p> The {@link #format(java.util.Locale,String,Object...) format} method2293* for this object which has a locale argument does not change this value.2294*2295* @return {@code null} if no localization is applied, otherwise a2296* locale2297*2298* @throws FormatterClosedException2299* If this formatter has been closed by invoking its {@link2300* #close()} method2301*/2302public Locale locale() {2303ensureOpen();2304return l;2305}23062307/**2308* Returns the destination for the output.2309*2310* @return The destination for the output2311*2312* @throws FormatterClosedException2313* If this formatter has been closed by invoking its {@link2314* #close()} method2315*/2316public Appendable out() {2317ensureOpen();2318return a;2319}23202321/**2322* Returns the result of invoking {@code toString()} on the destination2323* for the output. For example, the following code formats text into a2324* {@link StringBuilder} then retrieves the resultant string:2325*2326* <blockquote><pre>2327* Formatter f = new Formatter();2328* f.format("Last reboot at %tc", lastRebootDate);2329* String s = f.toString();2330* // -> s == "Last reboot at Sat Jan 01 00:00:00 PST 2000"2331* </pre></blockquote>2332*2333* <p> An invocation of this method behaves in exactly the same way as the2334* invocation2335*2336* <pre>2337* out().toString() </pre>2338*2339* <p> Depending on the specification of {@code toString} for the {@link2340* Appendable}, the returned string may or may not contain the characters2341* written to the destination. For instance, buffers typically return2342* their contents in {@code toString()}, but streams cannot since the2343* data is discarded.2344*2345* @return The result of invoking {@code toString()} on the destination2346* for the output2347*2348* @throws FormatterClosedException2349* If this formatter has been closed by invoking its {@link2350* #close()} method2351*/2352public String toString() {2353ensureOpen();2354return a.toString();2355}23562357/**2358* Flushes this formatter. If the destination implements the {@link2359* java.io.Flushable} interface, its {@code flush} method will be invoked.2360*2361* <p> Flushing a formatter writes any buffered output in the destination2362* to the underlying stream.2363*2364* @throws FormatterClosedException2365* If this formatter has been closed by invoking its {@link2366* #close()} method2367*/2368public void flush() {2369ensureOpen();2370if (a instanceof Flushable) {2371try {2372((Flushable)a).flush();2373} catch (IOException ioe) {2374lastException = ioe;2375}2376}2377}23782379/**2380* Closes this formatter. If the destination implements the {@link2381* java.io.Closeable} interface, its {@code close} method will be invoked.2382*2383* <p> Closing a formatter allows it to release resources it may be holding2384* (such as open files). If the formatter is already closed, then invoking2385* this method has no effect.2386*2387* <p> Attempting to invoke any methods except {@link #ioException()} in2388* this formatter after it has been closed will result in a {@link2389* FormatterClosedException}.2390*/2391public void close() {2392if (a == null)2393return;2394try {2395if (a instanceof Closeable)2396((Closeable)a).close();2397} catch (IOException ioe) {2398lastException = ioe;2399} finally {2400a = null;2401}2402}24032404private void ensureOpen() {2405if (a == null)2406throw new FormatterClosedException();2407}24082409/**2410* Returns the {@code IOException} last thrown by this formatter's {@link2411* Appendable}.2412*2413* <p> If the destination's {@code append()} method never throws2414* {@code IOException}, then this method will always return {@code null}.2415*2416* @return The last exception thrown by the Appendable or {@code null} if2417* no such exception exists.2418*/2419public IOException ioException() {2420return lastException;2421}24222423/**2424* Writes a formatted string to this object's destination using the2425* specified format string and arguments. The locale used is the one2426* defined during the construction of this formatter.2427*2428* @param format2429* A format string as described in <a href="#syntax">Format string2430* syntax</a>.2431*2432* @param args2433* Arguments referenced by the format specifiers in the format2434* string. If there are more arguments than format specifiers, the2435* extra arguments are ignored. The maximum number of arguments is2436* limited by the maximum dimension of a Java array as defined by2437* <cite>The Java™ Virtual Machine Specification</cite>.2438*2439* @throws IllegalFormatException2440* If a format string contains an illegal syntax, a format2441* specifier that is incompatible with the given arguments,2442* insufficient arguments given the format string, or other2443* illegal conditions. For specification of all possible2444* formatting errors, see the <a href="#detail">Details</a>2445* section of the formatter class specification.2446*2447* @throws FormatterClosedException2448* If this formatter has been closed by invoking its {@link2449* #close()} method2450*2451* @return This formatter2452*/2453public Formatter format(String format, Object ... args) {2454return format(l, format, args);2455}24562457/**2458* Writes a formatted string to this object's destination using the2459* specified locale, format string, and arguments.2460*2461* @param l2462* The {@linkplain java.util.Locale locale} to apply during2463* formatting. If {@code l} is {@code null} then no localization2464* is applied. This does not change this object's locale that was2465* set during construction.2466*2467* @param format2468* A format string as described in <a href="#syntax">Format string2469* syntax</a>2470*2471* @param args2472* Arguments referenced by the format specifiers in the format2473* string. If there are more arguments than format specifiers, the2474* extra arguments are ignored. The maximum number of arguments is2475* limited by the maximum dimension of a Java array as defined by2476* <cite>The Java™ Virtual Machine Specification</cite>.2477*2478* @throws IllegalFormatException2479* If a format string contains an illegal syntax, a format2480* specifier that is incompatible with the given arguments,2481* insufficient arguments given the format string, or other2482* illegal conditions. For specification of all possible2483* formatting errors, see the <a href="#detail">Details</a>2484* section of the formatter class specification.2485*2486* @throws FormatterClosedException2487* If this formatter has been closed by invoking its {@link2488* #close()} method2489*2490* @return This formatter2491*/2492public Formatter format(Locale l, String format, Object ... args) {2493ensureOpen();24942495// index of last argument referenced2496int last = -1;2497// last ordinary index2498int lasto = -1;24992500FormatString[] fsa = parse(format);2501for (int i = 0; i < fsa.length; i++) {2502FormatString fs = fsa[i];2503int index = fs.index();2504try {2505switch (index) {2506case -2: // fixed string, "%n", or "%%"2507fs.print(null, l);2508break;2509case -1: // relative index2510if (last < 0 || (args != null && last > args.length - 1))2511throw new MissingFormatArgumentException(fs.toString());2512fs.print((args == null ? null : args[last]), l);2513break;2514case 0: // ordinary index2515lasto++;2516last = lasto;2517if (args != null && lasto > args.length - 1)2518throw new MissingFormatArgumentException(fs.toString());2519fs.print((args == null ? null : args[lasto]), l);2520break;2521default: // explicit index2522last = index - 1;2523if (args != null && last > args.length - 1)2524throw new MissingFormatArgumentException(fs.toString());2525fs.print((args == null ? null : args[last]), l);2526break;2527}2528} catch (IOException x) {2529lastException = x;2530}2531}2532return this;2533}25342535// %[argument_index$][flags][width][.precision][t]conversion2536private static final String formatSpecifier2537= "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";25382539private static Pattern fsPattern = Pattern.compile(formatSpecifier);25402541/**2542* Finds format specifiers in the format string.2543*/2544private FormatString[] parse(String s) {2545ArrayList<FormatString> al = new ArrayList<>();2546Matcher m = fsPattern.matcher(s);2547for (int i = 0, len = s.length(); i < len; ) {2548if (m.find(i)) {2549// Anything between the start of the string and the beginning2550// of the format specifier is either fixed text or contains2551// an invalid format string.2552if (m.start() != i) {2553// Make sure we didn't miss any invalid format specifiers2554checkText(s, i, m.start());2555// Assume previous characters were fixed text2556al.add(new FixedString(s.substring(i, m.start())));2557}25582559al.add(new FormatSpecifier(m));2560i = m.end();2561} else {2562// No more valid format specifiers. Check for possible invalid2563// format specifiers.2564checkText(s, i, len);2565// The rest of the string is fixed text2566al.add(new FixedString(s.substring(i)));2567break;2568}2569}2570return al.toArray(new FormatString[al.size()]);2571}25722573private static void checkText(String s, int start, int end) {2574for (int i = start; i < end; i++) {2575// Any '%' found in the region starts an invalid format specifier.2576if (s.charAt(i) == '%') {2577char c = (i == end - 1) ? '%' : s.charAt(i + 1);2578throw new UnknownFormatConversionException(String.valueOf(c));2579}2580}2581}25822583private interface FormatString {2584int index();2585void print(Object arg, Locale l) throws IOException;2586String toString();2587}25882589private class FixedString implements FormatString {2590private String s;2591FixedString(String s) { this.s = s; }2592public int index() { return -2; }2593public void print(Object arg, Locale l)2594throws IOException { a.append(s); }2595public String toString() { return s; }2596}25972598/**2599* Enum for {@code BigDecimal} formatting.2600*/2601public enum BigDecimalLayoutForm {2602/**2603* Format the {@code BigDecimal} in computerized scientific notation.2604*/2605SCIENTIFIC,26062607/**2608* Format the {@code BigDecimal} as a decimal number.2609*/2610DECIMAL_FLOAT2611};26122613private class FormatSpecifier implements FormatString {2614private int index = -1;2615private Flags f = Flags.NONE;2616private int width;2617private int precision;2618private boolean dt = false;2619private char c;26202621private int index(String s) {2622if (s != null) {2623try {2624index = Integer.parseInt(s.substring(0, s.length() - 1));2625} catch (NumberFormatException x) {2626assert(false);2627}2628} else {2629index = 0;2630}2631return index;2632}26332634public int index() {2635return index;2636}26372638private Flags flags(String s) {2639f = Flags.parse(s);2640if (f.contains(Flags.PREVIOUS))2641index = -1;2642return f;2643}26442645Flags flags() {2646return f;2647}26482649private int width(String s) {2650width = -1;2651if (s != null) {2652try {2653width = Integer.parseInt(s);2654if (width < 0)2655throw new IllegalFormatWidthException(width);2656} catch (NumberFormatException x) {2657assert(false);2658}2659}2660return width;2661}26622663int width() {2664return width;2665}26662667private int precision(String s) {2668precision = -1;2669if (s != null) {2670try {2671// remove the '.'2672precision = Integer.parseInt(s.substring(1));2673if (precision < 0)2674throw new IllegalFormatPrecisionException(precision);2675} catch (NumberFormatException x) {2676assert(false);2677}2678}2679return precision;2680}26812682int precision() {2683return precision;2684}26852686private char conversion(String s) {2687c = s.charAt(0);2688if (!dt) {2689if (!Conversion.isValid(c))2690throw new UnknownFormatConversionException(String.valueOf(c));2691if (Character.isUpperCase(c))2692f.add(Flags.UPPERCASE);2693c = Character.toLowerCase(c);2694if (Conversion.isText(c))2695index = -2;2696}2697return c;2698}26992700private char conversion() {2701return c;2702}27032704FormatSpecifier(Matcher m) {2705int idx = 1;27062707index(m.group(idx++));2708flags(m.group(idx++));2709width(m.group(idx++));2710precision(m.group(idx++));27112712String tT = m.group(idx++);2713if (tT != null) {2714dt = true;2715if (tT.equals("T"))2716f.add(Flags.UPPERCASE);2717}27182719conversion(m.group(idx));27202721if (dt)2722checkDateTime();2723else if (Conversion.isGeneral(c))2724checkGeneral();2725else if (Conversion.isCharacter(c))2726checkCharacter();2727else if (Conversion.isInteger(c))2728checkInteger();2729else if (Conversion.isFloat(c))2730checkFloat();2731else if (Conversion.isText(c))2732checkText();2733else2734throw new UnknownFormatConversionException(String.valueOf(c));2735}27362737public void print(Object arg, Locale l) throws IOException {2738if (dt) {2739printDateTime(arg, l);2740return;2741}2742switch(c) {2743case Conversion.DECIMAL_INTEGER:2744case Conversion.OCTAL_INTEGER:2745case Conversion.HEXADECIMAL_INTEGER:2746printInteger(arg, l);2747break;2748case Conversion.SCIENTIFIC:2749case Conversion.GENERAL:2750case Conversion.DECIMAL_FLOAT:2751case Conversion.HEXADECIMAL_FLOAT:2752printFloat(arg, l);2753break;2754case Conversion.CHARACTER:2755case Conversion.CHARACTER_UPPER:2756printCharacter(arg);2757break;2758case Conversion.BOOLEAN:2759printBoolean(arg);2760break;2761case Conversion.STRING:2762printString(arg, l);2763break;2764case Conversion.HASHCODE:2765printHashCode(arg);2766break;2767case Conversion.LINE_SEPARATOR:2768a.append(System.lineSeparator());2769break;2770case Conversion.PERCENT_SIGN:2771a.append('%');2772break;2773default:2774assert false;2775}2776}27772778private void printInteger(Object arg, Locale l) throws IOException {2779if (arg == null)2780print("null");2781else if (arg instanceof Byte)2782print(((Byte)arg).byteValue(), l);2783else if (arg instanceof Short)2784print(((Short)arg).shortValue(), l);2785else if (arg instanceof Integer)2786print(((Integer)arg).intValue(), l);2787else if (arg instanceof Long)2788print(((Long)arg).longValue(), l);2789else if (arg instanceof BigInteger)2790print(((BigInteger)arg), l);2791else2792failConversion(c, arg);2793}27942795private void printFloat(Object arg, Locale l) throws IOException {2796if (arg == null)2797print("null");2798else if (arg instanceof Float)2799print(((Float)arg).floatValue(), l);2800else if (arg instanceof Double)2801print(((Double)arg).doubleValue(), l);2802else if (arg instanceof BigDecimal)2803print(((BigDecimal)arg), l);2804else2805failConversion(c, arg);2806}28072808private void printDateTime(Object arg, Locale l) throws IOException {2809if (arg == null) {2810print("null");2811return;2812}2813Calendar cal = null;28142815// Instead of Calendar.setLenient(true), perhaps we should2816// wrap the IllegalArgumentException that might be thrown?2817if (arg instanceof Long) {2818// Note that the following method uses an instance of the2819// default time zone (TimeZone.getDefaultRef().2820cal = Calendar.getInstance(l == null ? Locale.US : l);2821cal.setTimeInMillis((Long)arg);2822} else if (arg instanceof Date) {2823// Note that the following method uses an instance of the2824// default time zone (TimeZone.getDefaultRef().2825cal = Calendar.getInstance(l == null ? Locale.US : l);2826cal.setTime((Date)arg);2827} else if (arg instanceof Calendar) {2828cal = (Calendar) ((Calendar) arg).clone();2829cal.setLenient(true);2830} else if (arg instanceof TemporalAccessor) {2831print((TemporalAccessor) arg, c, l);2832return;2833} else {2834failConversion(c, arg);2835}2836// Use the provided locale so that invocations of2837// localizedMagnitude() use optimizations for null.2838print(cal, c, l);2839}28402841private void printCharacter(Object arg) throws IOException {2842if (arg == null) {2843print("null");2844return;2845}2846String s = null;2847if (arg instanceof Character) {2848s = ((Character)arg).toString();2849} else if (arg instanceof Byte) {2850byte i = ((Byte)arg).byteValue();2851if (Character.isValidCodePoint(i))2852s = new String(Character.toChars(i));2853else2854throw new IllegalFormatCodePointException(i);2855} else if (arg instanceof Short) {2856short i = ((Short)arg).shortValue();2857if (Character.isValidCodePoint(i))2858s = new String(Character.toChars(i));2859else2860throw new IllegalFormatCodePointException(i);2861} else if (arg instanceof Integer) {2862int i = ((Integer)arg).intValue();2863if (Character.isValidCodePoint(i))2864s = new String(Character.toChars(i));2865else2866throw new IllegalFormatCodePointException(i);2867} else {2868failConversion(c, arg);2869}2870print(s);2871}28722873private void printString(Object arg, Locale l) throws IOException {2874if (arg instanceof Formattable) {2875Formatter fmt = Formatter.this;2876if (fmt.locale() != l)2877fmt = new Formatter(fmt.out(), l);2878((Formattable)arg).formatTo(fmt, f.valueOf(), width, precision);2879} else {2880if (f.contains(Flags.ALTERNATE))2881failMismatch(Flags.ALTERNATE, 's');2882if (arg == null)2883print("null");2884else2885print(arg.toString());2886}2887}28882889private void printBoolean(Object arg) throws IOException {2890String s;2891if (arg != null)2892s = ((arg instanceof Boolean)2893? ((Boolean)arg).toString()2894: Boolean.toString(true));2895else2896s = Boolean.toString(false);2897print(s);2898}28992900private void printHashCode(Object arg) throws IOException {2901String s = (arg == null2902? "null"2903: Integer.toHexString(arg.hashCode()));2904print(s);2905}29062907private void print(String s) throws IOException {2908if (precision != -1 && precision < s.length())2909s = s.substring(0, precision);2910if (f.contains(Flags.UPPERCASE))2911s = s.toUpperCase();2912a.append(justify(s));2913}29142915private String justify(String s) {2916if (width == -1)2917return s;2918StringBuilder sb = new StringBuilder();2919boolean pad = f.contains(Flags.LEFT_JUSTIFY);2920int sp = width - s.length();2921if (!pad)2922for (int i = 0; i < sp; i++) sb.append(' ');2923sb.append(s);2924if (pad)2925for (int i = 0; i < sp; i++) sb.append(' ');2926return sb.toString();2927}29282929public String toString() {2930StringBuilder sb = new StringBuilder("%");2931// Flags.UPPERCASE is set internally for legal conversions.2932Flags dupf = f.dup().remove(Flags.UPPERCASE);2933sb.append(dupf.toString());2934if (index > 0)2935sb.append(index).append('$');2936if (width != -1)2937sb.append(width);2938if (precision != -1)2939sb.append('.').append(precision);2940if (dt)2941sb.append(f.contains(Flags.UPPERCASE) ? 'T' : 't');2942sb.append(f.contains(Flags.UPPERCASE)2943? Character.toUpperCase(c) : c);2944return sb.toString();2945}29462947private void checkGeneral() {2948if ((c == Conversion.BOOLEAN || c == Conversion.HASHCODE)2949&& f.contains(Flags.ALTERNATE))2950failMismatch(Flags.ALTERNATE, c);2951// '-' requires a width2952if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))2953throw new MissingFormatWidthException(toString());2954checkBadFlags(Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD,2955Flags.GROUP, Flags.PARENTHESES);2956}29572958private void checkDateTime() {2959if (precision != -1)2960throw new IllegalFormatPrecisionException(precision);2961if (!DateTime.isValid(c))2962throw new UnknownFormatConversionException("t" + c);2963checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE,2964Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES);2965// '-' requires a width2966if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))2967throw new MissingFormatWidthException(toString());2968}29692970private void checkCharacter() {2971if (precision != -1)2972throw new IllegalFormatPrecisionException(precision);2973checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE,2974Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES);2975// '-' requires a width2976if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))2977throw new MissingFormatWidthException(toString());2978}29792980private void checkInteger() {2981checkNumeric();2982if (precision != -1)2983throw new IllegalFormatPrecisionException(precision);29842985if (c == Conversion.DECIMAL_INTEGER)2986checkBadFlags(Flags.ALTERNATE);2987else if (c == Conversion.OCTAL_INTEGER)2988checkBadFlags(Flags.GROUP);2989else2990checkBadFlags(Flags.GROUP);2991}29922993private void checkBadFlags(Flags ... badFlags) {2994for (int i = 0; i < badFlags.length; i++)2995if (f.contains(badFlags[i]))2996failMismatch(badFlags[i], c);2997}29982999private void checkFloat() {3000checkNumeric();3001if (c == Conversion.DECIMAL_FLOAT) {3002} else if (c == Conversion.HEXADECIMAL_FLOAT) {3003checkBadFlags(Flags.PARENTHESES, Flags.GROUP);3004} else if (c == Conversion.SCIENTIFIC) {3005checkBadFlags(Flags.GROUP);3006} else if (c == Conversion.GENERAL) {3007checkBadFlags(Flags.ALTERNATE);3008}3009}30103011private void checkNumeric() {3012if (width != -1 && width < 0)3013throw new IllegalFormatWidthException(width);30143015if (precision != -1 && precision < 0)3016throw new IllegalFormatPrecisionException(precision);30173018// '-' and '0' require a width3019if (width == -13020&& (f.contains(Flags.LEFT_JUSTIFY) || f.contains(Flags.ZERO_PAD)))3021throw new MissingFormatWidthException(toString());30223023// bad combination3024if ((f.contains(Flags.PLUS) && f.contains(Flags.LEADING_SPACE))3025|| (f.contains(Flags.LEFT_JUSTIFY) && f.contains(Flags.ZERO_PAD)))3026throw new IllegalFormatFlagsException(f.toString());3027}30283029private void checkText() {3030if (precision != -1)3031throw new IllegalFormatPrecisionException(precision);3032switch (c) {3033case Conversion.PERCENT_SIGN:3034if (f.valueOf() != Flags.LEFT_JUSTIFY.valueOf()3035&& f.valueOf() != Flags.NONE.valueOf())3036throw new IllegalFormatFlagsException(f.toString());3037// '-' requires a width3038if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))3039throw new MissingFormatWidthException(toString());3040break;3041case Conversion.LINE_SEPARATOR:3042if (width != -1)3043throw new IllegalFormatWidthException(width);3044if (f.valueOf() != Flags.NONE.valueOf())3045throw new IllegalFormatFlagsException(f.toString());3046break;3047default:3048assert false;3049}3050}30513052private void print(byte value, Locale l) throws IOException {3053long v = value;3054if (value < 03055&& (c == Conversion.OCTAL_INTEGER3056|| c == Conversion.HEXADECIMAL_INTEGER)) {3057v += (1L << 8);3058assert v >= 0 : v;3059}3060print(v, l);3061}30623063private void print(short value, Locale l) throws IOException {3064long v = value;3065if (value < 03066&& (c == Conversion.OCTAL_INTEGER3067|| c == Conversion.HEXADECIMAL_INTEGER)) {3068v += (1L << 16);3069assert v >= 0 : v;3070}3071print(v, l);3072}30733074private void print(int value, Locale l) throws IOException {3075long v = value;3076if (value < 03077&& (c == Conversion.OCTAL_INTEGER3078|| c == Conversion.HEXADECIMAL_INTEGER)) {3079v += (1L << 32);3080assert v >= 0 : v;3081}3082print(v, l);3083}30843085private void print(long value, Locale l) throws IOException {30863087StringBuilder sb = new StringBuilder();30883089if (c == Conversion.DECIMAL_INTEGER) {3090boolean neg = value < 0;3091char[] va;3092if (value < 0)3093va = Long.toString(value, 10).substring(1).toCharArray();3094else3095va = Long.toString(value, 10).toCharArray();30963097// leading sign indicator3098leadingSign(sb, neg);30993100// the value3101localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l);31023103// trailing sign indicator3104trailingSign(sb, neg);3105} else if (c == Conversion.OCTAL_INTEGER) {3106checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,3107Flags.PLUS);3108String s = Long.toOctalString(value);3109int len = (f.contains(Flags.ALTERNATE)3110? s.length() + 13111: s.length());31123113// apply ALTERNATE (radix indicator for octal) before ZERO_PAD3114if (f.contains(Flags.ALTERNATE))3115sb.append('0');3116if (f.contains(Flags.ZERO_PAD))3117for (int i = 0; i < width - len; i++) sb.append('0');3118sb.append(s);3119} else if (c == Conversion.HEXADECIMAL_INTEGER) {3120checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,3121Flags.PLUS);3122String s = Long.toHexString(value);3123int len = (f.contains(Flags.ALTERNATE)3124? s.length() + 23125: s.length());31263127// apply ALTERNATE (radix indicator for hex) before ZERO_PAD3128if (f.contains(Flags.ALTERNATE))3129sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");3130if (f.contains(Flags.ZERO_PAD))3131for (int i = 0; i < width - len; i++) sb.append('0');3132if (f.contains(Flags.UPPERCASE))3133s = s.toUpperCase();3134sb.append(s);3135}31363137// justify based on width3138a.append(justify(sb.toString()));3139}31403141// neg := val < 03142private StringBuilder leadingSign(StringBuilder sb, boolean neg) {3143if (!neg) {3144if (f.contains(Flags.PLUS)) {3145sb.append('+');3146} else if (f.contains(Flags.LEADING_SPACE)) {3147sb.append(' ');3148}3149} else {3150if (f.contains(Flags.PARENTHESES))3151sb.append('(');3152else3153sb.append('-');3154}3155return sb;3156}31573158// neg := val < 03159private StringBuilder trailingSign(StringBuilder sb, boolean neg) {3160if (neg && f.contains(Flags.PARENTHESES))3161sb.append(')');3162return sb;3163}31643165private void print(BigInteger value, Locale l) throws IOException {3166StringBuilder sb = new StringBuilder();3167boolean neg = value.signum() == -1;3168BigInteger v = value.abs();31693170// leading sign indicator3171leadingSign(sb, neg);31723173// the value3174if (c == Conversion.DECIMAL_INTEGER) {3175char[] va = v.toString().toCharArray();3176localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l);3177} else if (c == Conversion.OCTAL_INTEGER) {3178String s = v.toString(8);31793180int len = s.length() + sb.length();3181if (neg && f.contains(Flags.PARENTHESES))3182len++;31833184// apply ALTERNATE (radix indicator for octal) before ZERO_PAD3185if (f.contains(Flags.ALTERNATE)) {3186len++;3187sb.append('0');3188}3189if (f.contains(Flags.ZERO_PAD)) {3190for (int i = 0; i < width - len; i++)3191sb.append('0');3192}3193sb.append(s);3194} else if (c == Conversion.HEXADECIMAL_INTEGER) {3195String s = v.toString(16);31963197int len = s.length() + sb.length();3198if (neg && f.contains(Flags.PARENTHESES))3199len++;32003201// apply ALTERNATE (radix indicator for hex) before ZERO_PAD3202if (f.contains(Flags.ALTERNATE)) {3203len += 2;3204sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");3205}3206if (f.contains(Flags.ZERO_PAD))3207for (int i = 0; i < width - len; i++)3208sb.append('0');3209if (f.contains(Flags.UPPERCASE))3210s = s.toUpperCase();3211sb.append(s);3212}32133214// trailing sign indicator3215trailingSign(sb, (value.signum() == -1));32163217// justify based on width3218a.append(justify(sb.toString()));3219}32203221private void print(float value, Locale l) throws IOException {3222print((double) value, l);3223}32243225private void print(double value, Locale l) throws IOException {3226StringBuilder sb = new StringBuilder();3227boolean neg = Double.compare(value, 0.0) == -1;32283229if (!Double.isNaN(value)) {3230double v = Math.abs(value);32313232// leading sign indicator3233leadingSign(sb, neg);32343235// the value3236if (!Double.isInfinite(v))3237print(sb, v, l, f, c, precision, neg);3238else3239sb.append(f.contains(Flags.UPPERCASE)3240? "INFINITY" : "Infinity");32413242// trailing sign indicator3243trailingSign(sb, neg);3244} else {3245sb.append(f.contains(Flags.UPPERCASE) ? "NAN" : "NaN");3246}32473248// justify based on width3249a.append(justify(sb.toString()));3250}32513252// !Double.isInfinite(value) && !Double.isNaN(value)3253private void print(StringBuilder sb, double value, Locale l,3254Flags f, char c, int precision, boolean neg)3255throws IOException3256{3257if (c == Conversion.SCIENTIFIC) {3258// Create a new FormattedFloatingDecimal with the desired3259// precision.3260int prec = (precision == -1 ? 6 : precision);32613262FormattedFloatingDecimal fd3263= FormattedFloatingDecimal.valueOf(value, prec,3264FormattedFloatingDecimal.Form.SCIENTIFIC);32653266char[] mant = addZeros(fd.getMantissa(), prec);32673268// If the precision is zero and the '#' flag is set, add the3269// requested decimal point.3270if (f.contains(Flags.ALTERNATE) && (prec == 0))3271mant = addDot(mant);32723273char[] exp = (value == 0.0)3274? new char[] {'+','0','0'} : fd.getExponent();32753276int newW = width;3277if (width != -1)3278newW = adjustWidth(width - exp.length - 1, f, neg);3279localizedMagnitude(sb, mant, f, newW, l);32803281sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');32823283Flags flags = f.dup().remove(Flags.GROUP);3284char sign = exp[0];3285assert(sign == '+' || sign == '-');3286sb.append(sign);32873288char[] tmp = new char[exp.length - 1];3289System.arraycopy(exp, 1, tmp, 0, exp.length - 1);3290sb.append(localizedMagnitude(null, tmp, flags, -1, l));3291} else if (c == Conversion.DECIMAL_FLOAT) {3292// Create a new FormattedFloatingDecimal with the desired3293// precision.3294int prec = (precision == -1 ? 6 : precision);32953296FormattedFloatingDecimal fd3297= FormattedFloatingDecimal.valueOf(value, prec,3298FormattedFloatingDecimal.Form.DECIMAL_FLOAT);32993300char[] mant = addZeros(fd.getMantissa(), prec);33013302// If the precision is zero and the '#' flag is set, add the3303// requested decimal point.3304if (f.contains(Flags.ALTERNATE) && (prec == 0))3305mant = addDot(mant);33063307int newW = width;3308if (width != -1)3309newW = adjustWidth(width, f, neg);3310localizedMagnitude(sb, mant, f, newW, l);3311} else if (c == Conversion.GENERAL) {3312int prec = precision;3313if (precision == -1)3314prec = 6;3315else if (precision == 0)3316prec = 1;33173318char[] exp;3319char[] mant;3320int expRounded;3321if (value == 0.0) {3322exp = null;3323mant = new char[] {'0'};3324expRounded = 0;3325} else {3326FormattedFloatingDecimal fd3327= FormattedFloatingDecimal.valueOf(value, prec,3328FormattedFloatingDecimal.Form.GENERAL);3329exp = fd.getExponent();3330mant = fd.getMantissa();3331expRounded = fd.getExponentRounded();3332}33333334if (exp != null) {3335prec -= 1;3336} else {3337prec -= expRounded + 1;3338}33393340mant = addZeros(mant, prec);3341// If the precision is zero and the '#' flag is set, add the3342// requested decimal point.3343if (f.contains(Flags.ALTERNATE) && (prec == 0))3344mant = addDot(mant);33453346int newW = width;3347if (width != -1) {3348if (exp != null)3349newW = adjustWidth(width - exp.length - 1, f, neg);3350else3351newW = adjustWidth(width, f, neg);3352}3353localizedMagnitude(sb, mant, f, newW, l);33543355if (exp != null) {3356sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');33573358Flags flags = f.dup().remove(Flags.GROUP);3359char sign = exp[0];3360assert(sign == '+' || sign == '-');3361sb.append(sign);33623363char[] tmp = new char[exp.length - 1];3364System.arraycopy(exp, 1, tmp, 0, exp.length - 1);3365sb.append(localizedMagnitude(null, tmp, flags, -1, l));3366}3367} else if (c == Conversion.HEXADECIMAL_FLOAT) {3368int prec = precision;3369if (precision == -1)3370// assume that we want all of the digits3371prec = 0;3372else if (precision == 0)3373prec = 1;33743375String s = hexDouble(value, prec);33763377char[] va;3378boolean upper = f.contains(Flags.UPPERCASE);3379sb.append(upper ? "0X" : "0x");33803381if (f.contains(Flags.ZERO_PAD))3382for (int i = 0; i < width - s.length() - 2; i++)3383sb.append('0');33843385int idx = s.indexOf('p');3386va = s.substring(0, idx).toCharArray();3387if (upper) {3388String tmp = new String(va);3389// don't localize hex3390tmp = tmp.toUpperCase(Locale.US);3391va = tmp.toCharArray();3392}3393sb.append(prec != 0 ? addZeros(va, prec) : va);3394sb.append(upper ? 'P' : 'p');3395sb.append(s.substring(idx+1));3396}3397}33983399// Add zeros to the requested precision.3400private char[] addZeros(char[] v, int prec) {3401// Look for the dot. If we don't find one, the we'll need to add3402// it before we add the zeros.3403int i;3404for (i = 0; i < v.length; i++) {3405if (v[i] == '.')3406break;3407}3408boolean needDot = false;3409if (i == v.length) {3410needDot = true;3411}34123413// Determine existing precision.3414int outPrec = v.length - i - (needDot ? 0 : 1);3415assert (outPrec <= prec);3416if (outPrec == prec)3417return v;34183419// Create new array with existing contents.3420char[] tmp3421= new char[v.length + prec - outPrec + (needDot ? 1 : 0)];3422System.arraycopy(v, 0, tmp, 0, v.length);34233424// Add dot if previously determined to be necessary.3425int start = v.length;3426if (needDot) {3427tmp[v.length] = '.';3428start++;3429}34303431// Add zeros.3432for (int j = start; j < tmp.length; j++)3433tmp[j] = '0';34343435return tmp;3436}34373438// Method assumes that d > 0.3439private String hexDouble(double d, int prec) {3440// Let Double.toHexString handle simple cases3441if(!Double.isFinite(d) || d == 0.0 || prec == 0 || prec >= 13)3442// remove "0x"3443return Double.toHexString(d).substring(2);3444else {3445assert(prec >= 1 && prec <= 12);34463447int exponent = Math.getExponent(d);3448boolean subnormal3449= (exponent == DoubleConsts.MIN_EXPONENT - 1);34503451// If this is subnormal input so normalize (could be faster to3452// do as integer operation).3453if (subnormal) {3454scaleUp = Math.scalb(1.0, 54);3455d *= scaleUp;3456// Calculate the exponent. This is not just exponent + 543457// since the former is not the normalized exponent.3458exponent = Math.getExponent(d);3459assert exponent >= DoubleConsts.MIN_EXPONENT &&3460exponent <= DoubleConsts.MAX_EXPONENT: exponent;3461}34623463int precision = 1 + prec*4;3464int shiftDistance3465= DoubleConsts.SIGNIFICAND_WIDTH - precision;3466assert(shiftDistance >= 1 && shiftDistance < DoubleConsts.SIGNIFICAND_WIDTH);34673468long doppel = Double.doubleToLongBits(d);3469// Deterime the number of bits to keep.3470long newSignif3471= (doppel & (DoubleConsts.EXP_BIT_MASK3472| DoubleConsts.SIGNIF_BIT_MASK))3473>> shiftDistance;3474// Bits to round away.3475long roundingBits = doppel & ~(~0L << shiftDistance);34763477// To decide how to round, look at the low-order bit of the3478// working significand, the highest order discarded bit (the3479// round bit) and whether any of the lower order discarded bits3480// are nonzero (the sticky bit).34813482boolean leastZero = (newSignif & 0x1L) == 0L;3483boolean round3484= ((1L << (shiftDistance - 1) ) & roundingBits) != 0L;3485boolean sticky = shiftDistance > 1 &&3486(~(1L<< (shiftDistance - 1)) & roundingBits) != 0;3487if((leastZero && round && sticky) || (!leastZero && round)) {3488newSignif++;3489}34903491long signBit = doppel & DoubleConsts.SIGN_BIT_MASK;3492newSignif = signBit | (newSignif << shiftDistance);3493double result = Double.longBitsToDouble(newSignif);34943495if (Double.isInfinite(result) ) {3496// Infinite result generated by rounding3497return "1.0p1024";3498} else {3499String res = Double.toHexString(result).substring(2);3500if (!subnormal)3501return res;3502else {3503// Create a normalized subnormal string.3504int idx = res.indexOf('p');3505if (idx == -1) {3506// No 'p' character in hex string.3507assert false;3508return null;3509} else {3510// Get exponent and append at the end.3511String exp = res.substring(idx + 1);3512int iexp = Integer.parseInt(exp) -54;3513return res.substring(0, idx) + "p"3514+ Integer.toString(iexp);3515}3516}3517}3518}3519}35203521private void print(BigDecimal value, Locale l) throws IOException {3522if (c == Conversion.HEXADECIMAL_FLOAT)3523failConversion(c, value);3524StringBuilder sb = new StringBuilder();3525boolean neg = value.signum() == -1;3526BigDecimal v = value.abs();3527// leading sign indicator3528leadingSign(sb, neg);35293530// the value3531print(sb, v, l, f, c, precision, neg);35323533// trailing sign indicator3534trailingSign(sb, neg);35353536// justify based on width3537a.append(justify(sb.toString()));3538}35393540// value > 03541private void print(StringBuilder sb, BigDecimal value, Locale l,3542Flags f, char c, int precision, boolean neg)3543throws IOException3544{3545if (c == Conversion.SCIENTIFIC) {3546// Create a new BigDecimal with the desired precision.3547int prec = (precision == -1 ? 6 : precision);3548int scale = value.scale();3549int origPrec = value.precision();3550int nzeros = 0;3551int compPrec;35523553if (prec > origPrec - 1) {3554compPrec = origPrec;3555nzeros = prec - (origPrec - 1);3556} else {3557compPrec = prec + 1;3558}35593560MathContext mc = new MathContext(compPrec);3561BigDecimal v3562= new BigDecimal(value.unscaledValue(), scale, mc);35633564BigDecimalLayout bdl3565= new BigDecimalLayout(v.unscaledValue(), v.scale(),3566BigDecimalLayoutForm.SCIENTIFIC);35673568char[] mant = bdl.mantissa();35693570// Add a decimal point if necessary. The mantissa may not3571// contain a decimal point if the scale is zero (the internal3572// representation has no fractional part) or the original3573// precision is one. Append a decimal point if '#' is set or if3574// we require zero padding to get to the requested precision.3575if ((origPrec == 1 || !bdl.hasDot())3576&& (nzeros > 0 || (f.contains(Flags.ALTERNATE))))3577mant = addDot(mant);35783579// Add trailing zeros in the case precision is greater than3580// the number of available digits after the decimal separator.3581mant = trailingZeros(mant, nzeros);35823583char[] exp = bdl.exponent();3584int newW = width;3585if (width != -1)3586newW = adjustWidth(width - exp.length - 1, f, neg);3587localizedMagnitude(sb, mant, f, newW, l);35883589sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');35903591Flags flags = f.dup().remove(Flags.GROUP);3592char sign = exp[0];3593assert(sign == '+' || sign == '-');3594sb.append(exp[0]);35953596char[] tmp = new char[exp.length - 1];3597System.arraycopy(exp, 1, tmp, 0, exp.length - 1);3598sb.append(localizedMagnitude(null, tmp, flags, -1, l));3599} else if (c == Conversion.DECIMAL_FLOAT) {3600// Create a new BigDecimal with the desired precision.3601int prec = (precision == -1 ? 6 : precision);3602int scale = value.scale();36033604if (scale > prec) {3605// more "scale" digits than the requested "precision"3606int compPrec = value.precision();3607if (compPrec <= scale) {3608// case of 0.xxxxxx3609value = value.setScale(prec, RoundingMode.HALF_UP);3610} else {3611compPrec -= (scale - prec);3612value = new BigDecimal(value.unscaledValue(),3613scale,3614new MathContext(compPrec));3615}3616}3617BigDecimalLayout bdl = new BigDecimalLayout(3618value.unscaledValue(),3619value.scale(),3620BigDecimalLayoutForm.DECIMAL_FLOAT);36213622char mant[] = bdl.mantissa();3623int nzeros = (bdl.scale() < prec ? prec - bdl.scale() : 0);36243625// Add a decimal point if necessary. The mantissa may not3626// contain a decimal point if the scale is zero (the internal3627// representation has no fractional part). Append a decimal3628// point if '#' is set or we require zero padding to get to the3629// requested precision.3630if (bdl.scale() == 0 && (f.contains(Flags.ALTERNATE) || nzeros > 0))3631mant = addDot(bdl.mantissa());36323633// Add trailing zeros if the precision is greater than the3634// number of available digits after the decimal separator.3635mant = trailingZeros(mant, nzeros);36363637localizedMagnitude(sb, mant, f, adjustWidth(width, f, neg), l);3638} else if (c == Conversion.GENERAL) {3639int prec = precision;3640if (precision == -1)3641prec = 6;3642else if (precision == 0)3643prec = 1;36443645BigDecimal tenToTheNegFour = BigDecimal.valueOf(1, 4);3646BigDecimal tenToThePrec = BigDecimal.valueOf(1, -prec);3647if ((value.equals(BigDecimal.ZERO))3648|| ((value.compareTo(tenToTheNegFour) != -1)3649&& (value.compareTo(tenToThePrec) == -1))) {36503651int e = - value.scale()3652+ (value.unscaledValue().toString().length() - 1);36533654// xxx.yyy3655// g precision (# sig digits) = #x + #y3656// f precision = #y3657// exponent = #x - 13658// => f precision = g precision - exponent - 13659// 0.000zzz3660// g precision (# sig digits) = #z3661// f precision = #0 (after '.') + #z3662// exponent = - #0 (after '.') - 13663// => f precision = g precision - exponent - 13664prec = prec - e - 1;36653666print(sb, value, l, f, Conversion.DECIMAL_FLOAT, prec,3667neg);3668} else {3669print(sb, value, l, f, Conversion.SCIENTIFIC, prec - 1, neg);3670}3671} else if (c == Conversion.HEXADECIMAL_FLOAT) {3672// This conversion isn't supported. The error should be3673// reported earlier.3674assert false;3675}3676}36773678private class BigDecimalLayout {3679private StringBuilder mant;3680private StringBuilder exp;3681private boolean dot = false;3682private int scale;36833684public BigDecimalLayout(BigInteger intVal, int scale, BigDecimalLayoutForm form) {3685layout(intVal, scale, form);3686}36873688public boolean hasDot() {3689return dot;3690}36913692public int scale() {3693return scale;3694}36953696// char[] with canonical string representation3697public char[] layoutChars() {3698StringBuilder sb = new StringBuilder(mant);3699if (exp != null) {3700sb.append('E');3701sb.append(exp);3702}3703return toCharArray(sb);3704}37053706public char[] mantissa() {3707return toCharArray(mant);3708}37093710// The exponent will be formatted as a sign ('+' or '-') followed3711// by the exponent zero-padded to include at least two digits.3712public char[] exponent() {3713return toCharArray(exp);3714}37153716private char[] toCharArray(StringBuilder sb) {3717if (sb == null)3718return null;3719char[] result = new char[sb.length()];3720sb.getChars(0, result.length, result, 0);3721return result;3722}37233724private void layout(BigInteger intVal, int scale, BigDecimalLayoutForm form) {3725char coeff[] = intVal.toString().toCharArray();3726this.scale = scale;37273728// Construct a buffer, with sufficient capacity for all cases.3729// If E-notation is needed, length will be: +1 if negative, +13730// if '.' needed, +2 for "E+", + up to 10 for adjusted3731// exponent. Otherwise it could have +1 if negative, plus3732// leading "0.00000"3733mant = new StringBuilder(coeff.length + 14);37343735if (scale == 0) {3736int len = coeff.length;3737if (len > 1) {3738mant.append(coeff[0]);3739if (form == BigDecimalLayoutForm.SCIENTIFIC) {3740mant.append('.');3741dot = true;3742mant.append(coeff, 1, len - 1);3743exp = new StringBuilder("+");3744if (len < 10)3745exp.append("0").append(len - 1);3746else3747exp.append(len - 1);3748} else {3749mant.append(coeff, 1, len - 1);3750}3751} else {3752mant.append(coeff);3753if (form == BigDecimalLayoutForm.SCIENTIFIC)3754exp = new StringBuilder("+00");3755}3756return;3757}3758long adjusted = -(long) scale + (coeff.length - 1);3759if (form == BigDecimalLayoutForm.DECIMAL_FLOAT) {3760// count of padding zeros3761int pad = scale - coeff.length;3762if (pad >= 0) {3763// 0.xxx form3764mant.append("0.");3765dot = true;3766for (; pad > 0 ; pad--) mant.append('0');3767mant.append(coeff);3768} else {3769if (-pad < coeff.length) {3770// xx.xx form3771mant.append(coeff, 0, -pad);3772mant.append('.');3773dot = true;3774mant.append(coeff, -pad, scale);3775} else {3776// xx form3777mant.append(coeff, 0, coeff.length);3778for (int i = 0; i < -scale; i++)3779mant.append('0');3780this.scale = 0;3781}3782}3783} else {3784// x.xxx form3785mant.append(coeff[0]);3786if (coeff.length > 1) {3787mant.append('.');3788dot = true;3789mant.append(coeff, 1, coeff.length-1);3790}3791exp = new StringBuilder();3792if (adjusted != 0) {3793long abs = Math.abs(adjusted);3794// require sign3795exp.append(adjusted < 0 ? '-' : '+');3796if (abs < 10)3797exp.append('0');3798exp.append(abs);3799} else {3800exp.append("+00");3801}3802}3803}3804}38053806private int adjustWidth(int width, Flags f, boolean neg) {3807int newW = width;3808if (newW != -1 && neg && f.contains(Flags.PARENTHESES))3809newW--;3810return newW;3811}38123813// Add a '.' to th mantissa if required3814private char[] addDot(char[] mant) {3815char[] tmp = mant;3816tmp = new char[mant.length + 1];3817System.arraycopy(mant, 0, tmp, 0, mant.length);3818tmp[tmp.length - 1] = '.';3819return tmp;3820}38213822// Add trailing zeros in the case precision is greater than the number3823// of available digits after the decimal separator.3824private char[] trailingZeros(char[] mant, int nzeros) {3825char[] tmp = mant;3826if (nzeros > 0) {3827tmp = new char[mant.length + nzeros];3828System.arraycopy(mant, 0, tmp, 0, mant.length);3829for (int i = mant.length; i < tmp.length; i++)3830tmp[i] = '0';3831}3832return tmp;3833}38343835private void print(Calendar t, char c, Locale l) throws IOException3836{3837StringBuilder sb = new StringBuilder();3838print(sb, t, c, l);38393840// justify based on width3841String s = justify(sb.toString());3842if (f.contains(Flags.UPPERCASE))3843s = s.toUpperCase();38443845a.append(s);3846}38473848private Appendable print(StringBuilder sb, Calendar t, char c,3849Locale l)3850throws IOException3851{3852if (sb == null)3853sb = new StringBuilder();3854switch (c) {3855case DateTime.HOUR_OF_DAY_0: // 'H' (00 - 23)3856case DateTime.HOUR_0: // 'I' (01 - 12)3857case DateTime.HOUR_OF_DAY: // 'k' (0 - 23) -- like H3858case DateTime.HOUR: { // 'l' (1 - 12) -- like I3859int i = t.get(Calendar.HOUR_OF_DAY);3860if (c == DateTime.HOUR_0 || c == DateTime.HOUR)3861i = (i == 0 || i == 12 ? 12 : i % 12);3862Flags flags = (c == DateTime.HOUR_OF_DAY_03863|| c == DateTime.HOUR_03864? Flags.ZERO_PAD3865: Flags.NONE);3866sb.append(localizedMagnitude(null, i, flags, 2, l));3867break;3868}3869case DateTime.MINUTE: { // 'M' (00 - 59)3870int i = t.get(Calendar.MINUTE);3871Flags flags = Flags.ZERO_PAD;3872sb.append(localizedMagnitude(null, i, flags, 2, l));3873break;3874}3875case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999)3876int i = t.get(Calendar.MILLISECOND) * 1000000;3877Flags flags = Flags.ZERO_PAD;3878sb.append(localizedMagnitude(null, i, flags, 9, l));3879break;3880}3881case DateTime.MILLISECOND: { // 'L' (000 - 999)3882int i = t.get(Calendar.MILLISECOND);3883Flags flags = Flags.ZERO_PAD;3884sb.append(localizedMagnitude(null, i, flags, 3, l));3885break;3886}3887case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?)3888long i = t.getTimeInMillis();3889Flags flags = Flags.NONE;3890sb.append(localizedMagnitude(null, i, flags, width, l));3891break;3892}3893case DateTime.AM_PM: { // 'p' (am or pm)3894// Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper3895String[] ampm = { "AM", "PM" };3896if (l != null && l != Locale.US) {3897DateFormatSymbols dfs = DateFormatSymbols.getInstance(l);3898ampm = dfs.getAmPmStrings();3899}3900String s = ampm[t.get(Calendar.AM_PM)];3901sb.append(s.toLowerCase(l != null ? l : Locale.US));3902break;3903}3904case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?)3905long i = t.getTimeInMillis() / 1000;3906Flags flags = Flags.NONE;3907sb.append(localizedMagnitude(null, i, flags, width, l));3908break;3909}3910case DateTime.SECOND: { // 'S' (00 - 60 - leap second)3911int i = t.get(Calendar.SECOND);3912Flags flags = Flags.ZERO_PAD;3913sb.append(localizedMagnitude(null, i, flags, 2, l));3914break;3915}3916case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus?3917int i = t.get(Calendar.ZONE_OFFSET) + t.get(Calendar.DST_OFFSET);3918boolean neg = i < 0;3919sb.append(neg ? '-' : '+');3920if (neg)3921i = -i;3922int min = i / 60000;3923// combine minute and hour into a single integer3924int offset = (min / 60) * 100 + (min % 60);3925Flags flags = Flags.ZERO_PAD;39263927sb.append(localizedMagnitude(null, offset, flags, 4, l));3928break;3929}3930case DateTime.ZONE: { // 'Z' (symbol)3931TimeZone tz = t.getTimeZone();3932sb.append(tz.getDisplayName((t.get(Calendar.DST_OFFSET) != 0),3933TimeZone.SHORT,3934(l == null) ? Locale.US : l));3935break;3936}39373938// Date3939case DateTime.NAME_OF_DAY_ABBREV: // 'a'3940case DateTime.NAME_OF_DAY: { // 'A'3941int i = t.get(Calendar.DAY_OF_WEEK);3942Locale lt = ((l == null) ? Locale.US : l);3943DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);3944if (c == DateTime.NAME_OF_DAY)3945sb.append(dfs.getWeekdays()[i]);3946else3947sb.append(dfs.getShortWeekdays()[i]);3948break;3949}3950case DateTime.NAME_OF_MONTH_ABBREV: // 'b'3951case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b3952case DateTime.NAME_OF_MONTH: { // 'B'3953int i = t.get(Calendar.MONTH);3954Locale lt = ((l == null) ? Locale.US : l);3955DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);3956if (c == DateTime.NAME_OF_MONTH)3957sb.append(dfs.getMonths()[i]);3958else3959sb.append(dfs.getShortMonths()[i]);3960break;3961}3962case DateTime.CENTURY: // 'C' (00 - 99)3963case DateTime.YEAR_2: // 'y' (00 - 99)3964case DateTime.YEAR_4: { // 'Y' (0000 - 9999)3965int i = t.get(Calendar.YEAR);3966int size = 2;3967switch (c) {3968case DateTime.CENTURY:3969i /= 100;3970break;3971case DateTime.YEAR_2:3972i %= 100;3973break;3974case DateTime.YEAR_4:3975size = 4;3976break;3977}3978Flags flags = Flags.ZERO_PAD;3979sb.append(localizedMagnitude(null, i, flags, size, l));3980break;3981}3982case DateTime.DAY_OF_MONTH_0: // 'd' (01 - 31)3983case DateTime.DAY_OF_MONTH: { // 'e' (1 - 31) -- like d3984int i = t.get(Calendar.DATE);3985Flags flags = (c == DateTime.DAY_OF_MONTH_03986? Flags.ZERO_PAD3987: Flags.NONE);3988sb.append(localizedMagnitude(null, i, flags, 2, l));3989break;3990}3991case DateTime.DAY_OF_YEAR: { // 'j' (001 - 366)3992int i = t.get(Calendar.DAY_OF_YEAR);3993Flags flags = Flags.ZERO_PAD;3994sb.append(localizedMagnitude(null, i, flags, 3, l));3995break;3996}3997case DateTime.MONTH: { // 'm' (01 - 12)3998int i = t.get(Calendar.MONTH) + 1;3999Flags flags = Flags.ZERO_PAD;4000sb.append(localizedMagnitude(null, i, flags, 2, l));4001break;4002}40034004// Composites4005case DateTime.TIME: // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS)4006case DateTime.TIME_24_HOUR: { // 'R' (hh:mm same as %H:%M)4007char sep = ':';4008print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep);4009print(sb, t, DateTime.MINUTE, l);4010if (c == DateTime.TIME) {4011sb.append(sep);4012print(sb, t, DateTime.SECOND, l);4013}4014break;4015}4016case DateTime.TIME_12_HOUR: { // 'r' (hh:mm:ss [AP]M)4017char sep = ':';4018print(sb, t, DateTime.HOUR_0, l).append(sep);4019print(sb, t, DateTime.MINUTE, l).append(sep);4020print(sb, t, DateTime.SECOND, l).append(' ');4021// this may be in wrong place for some locales4022StringBuilder tsb = new StringBuilder();4023print(tsb, t, DateTime.AM_PM, l);4024sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US));4025break;4026}4027case DateTime.DATE_TIME: { // 'c' (Sat Nov 04 12:02:33 EST 1999)4028char sep = ' ';4029print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep);4030print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep);4031print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);4032print(sb, t, DateTime.TIME, l).append(sep);4033print(sb, t, DateTime.ZONE, l).append(sep);4034print(sb, t, DateTime.YEAR_4, l);4035break;4036}4037case DateTime.DATE: { // 'D' (mm/dd/yy)4038char sep = '/';4039print(sb, t, DateTime.MONTH, l).append(sep);4040print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);4041print(sb, t, DateTime.YEAR_2, l);4042break;4043}4044case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d)4045char sep = '-';4046print(sb, t, DateTime.YEAR_4, l).append(sep);4047print(sb, t, DateTime.MONTH, l).append(sep);4048print(sb, t, DateTime.DAY_OF_MONTH_0, l);4049break;4050}4051default:4052assert false;4053}4054return sb;4055}40564057private void print(TemporalAccessor t, char c, Locale l) throws IOException {4058StringBuilder sb = new StringBuilder();4059print(sb, t, c, l);4060// justify based on width4061String s = justify(sb.toString());4062if (f.contains(Flags.UPPERCASE))4063s = s.toUpperCase();4064a.append(s);4065}40664067private Appendable print(StringBuilder sb, TemporalAccessor t, char c,4068Locale l) throws IOException {4069if (sb == null)4070sb = new StringBuilder();4071try {4072switch (c) {4073case DateTime.HOUR_OF_DAY_0: { // 'H' (00 - 23)4074int i = t.get(ChronoField.HOUR_OF_DAY);4075sb.append(localizedMagnitude(null, i, Flags.ZERO_PAD, 2, l));4076break;4077}4078case DateTime.HOUR_OF_DAY: { // 'k' (0 - 23) -- like H4079int i = t.get(ChronoField.HOUR_OF_DAY);4080sb.append(localizedMagnitude(null, i, Flags.NONE, 2, l));4081break;4082}4083case DateTime.HOUR_0: { // 'I' (01 - 12)4084int i = t.get(ChronoField.CLOCK_HOUR_OF_AMPM);4085sb.append(localizedMagnitude(null, i, Flags.ZERO_PAD, 2, l));4086break;4087}4088case DateTime.HOUR: { // 'l' (1 - 12) -- like I4089int i = t.get(ChronoField.CLOCK_HOUR_OF_AMPM);4090sb.append(localizedMagnitude(null, i, Flags.NONE, 2, l));4091break;4092}4093case DateTime.MINUTE: { // 'M' (00 - 59)4094int i = t.get(ChronoField.MINUTE_OF_HOUR);4095Flags flags = Flags.ZERO_PAD;4096sb.append(localizedMagnitude(null, i, flags, 2, l));4097break;4098}4099case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999)4100int i = t.get(ChronoField.MILLI_OF_SECOND) * 1000000;4101Flags flags = Flags.ZERO_PAD;4102sb.append(localizedMagnitude(null, i, flags, 9, l));4103break;4104}4105case DateTime.MILLISECOND: { // 'L' (000 - 999)4106int i = t.get(ChronoField.MILLI_OF_SECOND);4107Flags flags = Flags.ZERO_PAD;4108sb.append(localizedMagnitude(null, i, flags, 3, l));4109break;4110}4111case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?)4112long i = t.getLong(ChronoField.INSTANT_SECONDS) * 1000L +4113t.getLong(ChronoField.MILLI_OF_SECOND);4114Flags flags = Flags.NONE;4115sb.append(localizedMagnitude(null, i, flags, width, l));4116break;4117}4118case DateTime.AM_PM: { // 'p' (am or pm)4119// Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper4120String[] ampm = { "AM", "PM" };4121if (l != null && l != Locale.US) {4122DateFormatSymbols dfs = DateFormatSymbols.getInstance(l);4123ampm = dfs.getAmPmStrings();4124}4125String s = ampm[t.get(ChronoField.AMPM_OF_DAY)];4126sb.append(s.toLowerCase(l != null ? l : Locale.US));4127break;4128}4129case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?)4130long i = t.getLong(ChronoField.INSTANT_SECONDS);4131Flags flags = Flags.NONE;4132sb.append(localizedMagnitude(null, i, flags, width, l));4133break;4134}4135case DateTime.SECOND: { // 'S' (00 - 60 - leap second)4136int i = t.get(ChronoField.SECOND_OF_MINUTE);4137Flags flags = Flags.ZERO_PAD;4138sb.append(localizedMagnitude(null, i, flags, 2, l));4139break;4140}4141case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus?4142int i = t.get(ChronoField.OFFSET_SECONDS);4143boolean neg = i < 0;4144sb.append(neg ? '-' : '+');4145if (neg)4146i = -i;4147int min = i / 60;4148// combine minute and hour into a single integer4149int offset = (min / 60) * 100 + (min % 60);4150Flags flags = Flags.ZERO_PAD;4151sb.append(localizedMagnitude(null, offset, flags, 4, l));4152break;4153}4154case DateTime.ZONE: { // 'Z' (symbol)4155ZoneId zid = t.query(TemporalQueries.zone());4156if (zid == null) {4157throw new IllegalFormatConversionException(c, t.getClass());4158}4159if (!(zid instanceof ZoneOffset) &&4160t.isSupported(ChronoField.INSTANT_SECONDS)) {4161Instant instant = Instant.from(t);4162sb.append(TimeZone.getTimeZone(zid.getId())4163.getDisplayName(zid.getRules().isDaylightSavings(instant),4164TimeZone.SHORT,4165(l == null) ? Locale.US : l));4166break;4167}4168sb.append(zid.getId());4169break;4170}4171// Date4172case DateTime.NAME_OF_DAY_ABBREV: // 'a'4173case DateTime.NAME_OF_DAY: { // 'A'4174int i = t.get(ChronoField.DAY_OF_WEEK) % 7 + 1;4175Locale lt = ((l == null) ? Locale.US : l);4176DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);4177if (c == DateTime.NAME_OF_DAY)4178sb.append(dfs.getWeekdays()[i]);4179else4180sb.append(dfs.getShortWeekdays()[i]);4181break;4182}4183case DateTime.NAME_OF_MONTH_ABBREV: // 'b'4184case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b4185case DateTime.NAME_OF_MONTH: { // 'B'4186int i = t.get(ChronoField.MONTH_OF_YEAR) - 1;4187Locale lt = ((l == null) ? Locale.US : l);4188DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);4189if (c == DateTime.NAME_OF_MONTH)4190sb.append(dfs.getMonths()[i]);4191else4192sb.append(dfs.getShortMonths()[i]);4193break;4194}4195case DateTime.CENTURY: // 'C' (00 - 99)4196case DateTime.YEAR_2: // 'y' (00 - 99)4197case DateTime.YEAR_4: { // 'Y' (0000 - 9999)4198int i = t.get(ChronoField.YEAR_OF_ERA);4199int size = 2;4200switch (c) {4201case DateTime.CENTURY:4202i /= 100;4203break;4204case DateTime.YEAR_2:4205i %= 100;4206break;4207case DateTime.YEAR_4:4208size = 4;4209break;4210}4211Flags flags = Flags.ZERO_PAD;4212sb.append(localizedMagnitude(null, i, flags, size, l));4213break;4214}4215case DateTime.DAY_OF_MONTH_0: // 'd' (01 - 31)4216case DateTime.DAY_OF_MONTH: { // 'e' (1 - 31) -- like d4217int i = t.get(ChronoField.DAY_OF_MONTH);4218Flags flags = (c == DateTime.DAY_OF_MONTH_04219? Flags.ZERO_PAD4220: Flags.NONE);4221sb.append(localizedMagnitude(null, i, flags, 2, l));4222break;4223}4224case DateTime.DAY_OF_YEAR: { // 'j' (001 - 366)4225int i = t.get(ChronoField.DAY_OF_YEAR);4226Flags flags = Flags.ZERO_PAD;4227sb.append(localizedMagnitude(null, i, flags, 3, l));4228break;4229}4230case DateTime.MONTH: { // 'm' (01 - 12)4231int i = t.get(ChronoField.MONTH_OF_YEAR);4232Flags flags = Flags.ZERO_PAD;4233sb.append(localizedMagnitude(null, i, flags, 2, l));4234break;4235}42364237// Composites4238case DateTime.TIME: // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS)4239case DateTime.TIME_24_HOUR: { // 'R' (hh:mm same as %H:%M)4240char sep = ':';4241print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep);4242print(sb, t, DateTime.MINUTE, l);4243if (c == DateTime.TIME) {4244sb.append(sep);4245print(sb, t, DateTime.SECOND, l);4246}4247break;4248}4249case DateTime.TIME_12_HOUR: { // 'r' (hh:mm:ss [AP]M)4250char sep = ':';4251print(sb, t, DateTime.HOUR_0, l).append(sep);4252print(sb, t, DateTime.MINUTE, l).append(sep);4253print(sb, t, DateTime.SECOND, l).append(' ');4254// this may be in wrong place for some locales4255StringBuilder tsb = new StringBuilder();4256print(tsb, t, DateTime.AM_PM, l);4257sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US));4258break;4259}4260case DateTime.DATE_TIME: { // 'c' (Sat Nov 04 12:02:33 EST 1999)4261char sep = ' ';4262print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep);4263print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep);4264print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);4265print(sb, t, DateTime.TIME, l).append(sep);4266print(sb, t, DateTime.ZONE, l).append(sep);4267print(sb, t, DateTime.YEAR_4, l);4268break;4269}4270case DateTime.DATE: { // 'D' (mm/dd/yy)4271char sep = '/';4272print(sb, t, DateTime.MONTH, l).append(sep);4273print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);4274print(sb, t, DateTime.YEAR_2, l);4275break;4276}4277case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d)4278char sep = '-';4279print(sb, t, DateTime.YEAR_4, l).append(sep);4280print(sb, t, DateTime.MONTH, l).append(sep);4281print(sb, t, DateTime.DAY_OF_MONTH_0, l);4282break;4283}4284default:4285assert false;4286}4287} catch (DateTimeException x) {4288throw new IllegalFormatConversionException(c, t.getClass());4289}4290return sb;4291}42924293// -- Methods to support throwing exceptions --42944295private void failMismatch(Flags f, char c) {4296String fs = f.toString();4297throw new FormatFlagsConversionMismatchException(fs, c);4298}42994300private void failConversion(char c, Object arg) {4301throw new IllegalFormatConversionException(c, arg.getClass());4302}43034304private char getZero(Locale l) {4305if ((l != null) && !l.equals(locale())) {4306DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);4307return dfs.getZeroDigit();4308}4309return zero;4310}43114312private StringBuilder4313localizedMagnitude(StringBuilder sb, long value, Flags f,4314int width, Locale l)4315{4316char[] va = Long.toString(value, 10).toCharArray();4317return localizedMagnitude(sb, va, f, width, l);4318}43194320private StringBuilder4321localizedMagnitude(StringBuilder sb, char[] value, Flags f,4322int width, Locale l)4323{4324if (sb == null)4325sb = new StringBuilder();4326int begin = sb.length();43274328char zero = getZero(l);43294330// determine localized grouping separator and size4331char grpSep = '\0';4332int grpSize = -1;4333char decSep = '\0';43344335int len = value.length;4336int dot = len;4337for (int j = 0; j < len; j++) {4338if (value[j] == '.') {4339dot = j;4340break;4341}4342}43434344if (dot < len) {4345if (l == null || l.equals(Locale.US)) {4346decSep = '.';4347} else {4348DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);4349decSep = dfs.getDecimalSeparator();4350}4351}43524353if (f.contains(Flags.GROUP)) {4354if (l == null || l.equals(Locale.US)) {4355grpSep = ',';4356grpSize = 3;4357} else {4358DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);4359grpSep = dfs.getGroupingSeparator();4360DecimalFormat df = (DecimalFormat) NumberFormat.getIntegerInstance(l);4361grpSize = df.getGroupingSize();4362}4363}43644365// localize the digits inserting group separators as necessary4366for (int j = 0; j < len; j++) {4367if (j == dot) {4368sb.append(decSep);4369// no more group separators after the decimal separator4370grpSep = '\0';4371continue;4372}43734374char c = value[j];4375sb.append((char) ((c - '0') + zero));4376if (grpSep != '\0' && j != dot - 1 && ((dot - j) % grpSize == 1))4377sb.append(grpSep);4378}43794380// apply zero padding4381len = sb.length();4382if (width != -1 && f.contains(Flags.ZERO_PAD))4383for (int k = 0; k < width - len; k++)4384sb.insert(begin, zero);43854386return sb;4387}4388}43894390private static class Flags {4391private int flags;43924393static final Flags NONE = new Flags(0); // ''43944395// duplicate declarations from Formattable.java4396static final Flags LEFT_JUSTIFY = new Flags(1<<0); // '-'4397static final Flags UPPERCASE = new Flags(1<<1); // '^'4398static final Flags ALTERNATE = new Flags(1<<2); // '#'43994400// numerics4401static final Flags PLUS = new Flags(1<<3); // '+'4402static final Flags LEADING_SPACE = new Flags(1<<4); // ' '4403static final Flags ZERO_PAD = new Flags(1<<5); // '0'4404static final Flags GROUP = new Flags(1<<6); // ','4405static final Flags PARENTHESES = new Flags(1<<7); // '('44064407// indexing4408static final Flags PREVIOUS = new Flags(1<<8); // '<'44094410private Flags(int f) {4411flags = f;4412}44134414public int valueOf() {4415return flags;4416}44174418public boolean contains(Flags f) {4419return (flags & f.valueOf()) == f.valueOf();4420}44214422public Flags dup() {4423return new Flags(flags);4424}44254426private Flags add(Flags f) {4427flags |= f.valueOf();4428return this;4429}44304431public Flags remove(Flags f) {4432flags &= ~f.valueOf();4433return this;4434}44354436public static Flags parse(String s) {4437char[] ca = s.toCharArray();4438Flags f = new Flags(0);4439for (int i = 0; i < ca.length; i++) {4440Flags v = parse(ca[i]);4441if (f.contains(v))4442throw new DuplicateFormatFlagsException(v.toString());4443f.add(v);4444}4445return f;4446}44474448// parse those flags which may be provided by users4449private static Flags parse(char c) {4450switch (c) {4451case '-': return LEFT_JUSTIFY;4452case '#': return ALTERNATE;4453case '+': return PLUS;4454case ' ': return LEADING_SPACE;4455case '0': return ZERO_PAD;4456case ',': return GROUP;4457case '(': return PARENTHESES;4458case '<': return PREVIOUS;4459default:4460throw new UnknownFormatFlagsException(String.valueOf(c));4461}4462}44634464// Returns a string representation of the current {@code Flags}.4465public static String toString(Flags f) {4466return f.toString();4467}44684469public String toString() {4470StringBuilder sb = new StringBuilder();4471if (contains(LEFT_JUSTIFY)) sb.append('-');4472if (contains(UPPERCASE)) sb.append('^');4473if (contains(ALTERNATE)) sb.append('#');4474if (contains(PLUS)) sb.append('+');4475if (contains(LEADING_SPACE)) sb.append(' ');4476if (contains(ZERO_PAD)) sb.append('0');4477if (contains(GROUP)) sb.append(',');4478if (contains(PARENTHESES)) sb.append('(');4479if (contains(PREVIOUS)) sb.append('<');4480return sb.toString();4481}4482}44834484private static class Conversion {4485// Byte, Short, Integer, Long, BigInteger4486// (and associated primitives due to autoboxing)4487static final char DECIMAL_INTEGER = 'd';4488static final char OCTAL_INTEGER = 'o';4489static final char HEXADECIMAL_INTEGER = 'x';4490static final char HEXADECIMAL_INTEGER_UPPER = 'X';44914492// Float, Double, BigDecimal4493// (and associated primitives due to autoboxing)4494static final char SCIENTIFIC = 'e';4495static final char SCIENTIFIC_UPPER = 'E';4496static final char GENERAL = 'g';4497static final char GENERAL_UPPER = 'G';4498static final char DECIMAL_FLOAT = 'f';4499static final char HEXADECIMAL_FLOAT = 'a';4500static final char HEXADECIMAL_FLOAT_UPPER = 'A';45014502// Character, Byte, Short, Integer4503// (and associated primitives due to autoboxing)4504static final char CHARACTER = 'c';4505static final char CHARACTER_UPPER = 'C';45064507// java.util.Date, java.util.Calendar, long4508static final char DATE_TIME = 't';4509static final char DATE_TIME_UPPER = 'T';45104511// if (arg.TYPE != boolean) return boolean4512// if (arg != null) return true; else return false;4513static final char BOOLEAN = 'b';4514static final char BOOLEAN_UPPER = 'B';4515// if (arg instanceof Formattable) arg.formatTo()4516// else arg.toString();4517static final char STRING = 's';4518static final char STRING_UPPER = 'S';4519// arg.hashCode()4520static final char HASHCODE = 'h';4521static final char HASHCODE_UPPER = 'H';45224523static final char LINE_SEPARATOR = 'n';4524static final char PERCENT_SIGN = '%';45254526static boolean isValid(char c) {4527return (isGeneral(c) || isInteger(c) || isFloat(c) || isText(c)4528|| c == 't' || isCharacter(c));4529}45304531// Returns true iff the Conversion is applicable to all objects.4532static boolean isGeneral(char c) {4533switch (c) {4534case BOOLEAN:4535case BOOLEAN_UPPER:4536case STRING:4537case STRING_UPPER:4538case HASHCODE:4539case HASHCODE_UPPER:4540return true;4541default:4542return false;4543}4544}45454546// Returns true iff the Conversion is applicable to character.4547static boolean isCharacter(char c) {4548switch (c) {4549case CHARACTER:4550case CHARACTER_UPPER:4551return true;4552default:4553return false;4554}4555}45564557// Returns true iff the Conversion is an integer type.4558static boolean isInteger(char c) {4559switch (c) {4560case DECIMAL_INTEGER:4561case OCTAL_INTEGER:4562case HEXADECIMAL_INTEGER:4563case HEXADECIMAL_INTEGER_UPPER:4564return true;4565default:4566return false;4567}4568}45694570// Returns true iff the Conversion is a floating-point type.4571static boolean isFloat(char c) {4572switch (c) {4573case SCIENTIFIC:4574case SCIENTIFIC_UPPER:4575case GENERAL:4576case GENERAL_UPPER:4577case DECIMAL_FLOAT:4578case HEXADECIMAL_FLOAT:4579case HEXADECIMAL_FLOAT_UPPER:4580return true;4581default:4582return false;4583}4584}45854586// Returns true iff the Conversion does not require an argument4587static boolean isText(char c) {4588switch (c) {4589case LINE_SEPARATOR:4590case PERCENT_SIGN:4591return true;4592default:4593return false;4594}4595}4596}45974598private static class DateTime {4599static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23)4600static final char HOUR_0 = 'I'; // (01 - 12)4601static final char HOUR_OF_DAY = 'k'; // (0 - 23) -- like H4602static final char HOUR = 'l'; // (1 - 12) -- like I4603static final char MINUTE = 'M'; // (00 - 59)4604static final char NANOSECOND = 'N'; // (000000000 - 999999999)4605static final char MILLISECOND = 'L'; // jdk, not in gnu (000 - 999)4606static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?)4607static final char AM_PM = 'p'; // (am or pm)4608static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?)4609static final char SECOND = 'S'; // (00 - 60 - leap second)4610static final char TIME = 'T'; // (24 hour hh:mm:ss)4611static final char ZONE_NUMERIC = 'z'; // (-1200 - +1200) - ls minus?4612static final char ZONE = 'Z'; // (symbol)46134614// Date4615static final char NAME_OF_DAY_ABBREV = 'a'; // 'a'4616static final char NAME_OF_DAY = 'A'; // 'A'4617static final char NAME_OF_MONTH_ABBREV = 'b'; // 'b'4618static final char NAME_OF_MONTH = 'B'; // 'B'4619static final char CENTURY = 'C'; // (00 - 99)4620static final char DAY_OF_MONTH_0 = 'd'; // (01 - 31)4621static final char DAY_OF_MONTH = 'e'; // (1 - 31) -- like d4622// * static final char ISO_WEEK_OF_YEAR_2 = 'g'; // cross %y %V4623// * static final char ISO_WEEK_OF_YEAR_4 = 'G'; // cross %Y %V4624static final char NAME_OF_MONTH_ABBREV_X = 'h'; // -- same b4625static final char DAY_OF_YEAR = 'j'; // (001 - 366)4626static final char MONTH = 'm'; // (01 - 12)4627// * static final char DAY_OF_WEEK_1 = 'u'; // (1 - 7) Monday4628// * static final char WEEK_OF_YEAR_SUNDAY = 'U'; // (0 - 53) Sunday+4629// * static final char WEEK_OF_YEAR_MONDAY_01 = 'V'; // (01 - 53) Monday+4630// * static final char DAY_OF_WEEK_0 = 'w'; // (0 - 6) Sunday4631// * static final char WEEK_OF_YEAR_MONDAY = 'W'; // (00 - 53) Monday4632static final char YEAR_2 = 'y'; // (00 - 99)4633static final char YEAR_4 = 'Y'; // (0000 - 9999)46344635// Composites4636static final char TIME_12_HOUR = 'r'; // (hh:mm:ss [AP]M)4637static final char TIME_24_HOUR = 'R'; // (hh:mm same as %H:%M)4638// * static final char LOCALE_TIME = 'X'; // (%H:%M:%S) - parse format?4639static final char DATE_TIME = 'c';4640// (Sat Nov 04 12:02:33 EST 1999)4641static final char DATE = 'D'; // (mm/dd/yy)4642static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d)4643// * static final char LOCALE_DATE = 'x'; // (mm/dd/yy)46444645static boolean isValid(char c) {4646switch (c) {4647case HOUR_OF_DAY_0:4648case HOUR_0:4649case HOUR_OF_DAY:4650case HOUR:4651case MINUTE:4652case NANOSECOND:4653case MILLISECOND:4654case MILLISECOND_SINCE_EPOCH:4655case AM_PM:4656case SECONDS_SINCE_EPOCH:4657case SECOND:4658case TIME:4659case ZONE_NUMERIC:4660case ZONE:46614662// Date4663case NAME_OF_DAY_ABBREV:4664case NAME_OF_DAY:4665case NAME_OF_MONTH_ABBREV:4666case NAME_OF_MONTH:4667case CENTURY:4668case DAY_OF_MONTH_0:4669case DAY_OF_MONTH:4670// * case ISO_WEEK_OF_YEAR_2:4671// * case ISO_WEEK_OF_YEAR_4:4672case NAME_OF_MONTH_ABBREV_X:4673case DAY_OF_YEAR:4674case MONTH:4675// * case DAY_OF_WEEK_1:4676// * case WEEK_OF_YEAR_SUNDAY:4677// * case WEEK_OF_YEAR_MONDAY_01:4678// * case DAY_OF_WEEK_0:4679// * case WEEK_OF_YEAR_MONDAY:4680case YEAR_2:4681case YEAR_4:46824683// Composites4684case TIME_12_HOUR:4685case TIME_24_HOUR:4686// * case LOCALE_TIME:4687case DATE_TIME:4688case DATE:4689case ISO_STANDARD_DATE:4690// * case LOCALE_DATE:4691return true;4692default:4693return false;4694}4695}4696}4697}469846994700