Formatter.java revision 49965c1dc9da104344f4893a05e45795a5740d20
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27package java.util; 28 29import java.io.BufferedWriter; 30import java.io.Closeable; 31import java.io.IOException; 32import java.io.File; 33import java.io.FileOutputStream; 34import java.io.FileNotFoundException; 35import java.io.Flushable; 36import java.io.OutputStream; 37import java.io.OutputStreamWriter; 38import java.io.PrintStream; 39import java.io.UnsupportedEncodingException; 40import java.math.BigDecimal; 41import java.math.BigInteger; 42import java.math.MathContext; 43import java.math.RoundingMode; 44import java.nio.charset.Charset; 45import java.nio.charset.IllegalCharsetNameException; 46import java.nio.charset.UnsupportedCharsetException; 47import java.text.DateFormatSymbols; 48import java.text.DecimalFormat; 49import java.text.DecimalFormatSymbols; 50import java.text.NumberFormat; 51 52import libcore.icu.LocaleData; 53import sun.misc.FpUtils; 54import sun.misc.DoubleConsts; 55import sun.misc.FormattedFloatingDecimal; 56 57/** 58 * An interpreter for printf-style format strings. This class provides support 59 * for layout justification and alignment, common formats for numeric, string, 60 * and date/time data, and locale-specific output. Common Java types such as 61 * {@code byte}, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar} 62 * are supported. Limited formatting customization for arbitrary user types is 63 * provided through the {@link Formattable} interface. 64 * 65 * <p> Formatters are not necessarily safe for multithreaded access. Thread 66 * safety is optional and is the responsibility of users of methods in this 67 * class. 68 * 69 * <p> Formatted printing for the Java language is heavily inspired by C's 70 * {@code printf}. Although the format strings are similar to C, some 71 * customizations have been made to accommodate the Java language and exploit 72 * some of its features. Also, Java formatting is more strict than C's; for 73 * example, if a conversion is incompatible with a flag, an exception will be 74 * thrown. In C inapplicable flags are silently ignored. The format strings 75 * are thus intended to be recognizable to C programmers but not necessarily 76 * completely compatible with those in C. 77 * 78 * <p> Examples of expected usage: 79 * 80 * <blockquote><pre> 81 * StringBuilder sb = new StringBuilder(); 82 * // Send all output to the Appendable object sb 83 * Formatter formatter = new Formatter(sb, Locale.US); 84 * 85 * // Explicit argument indices may be used to re-order output. 86 * formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") 87 * // -> " d c b a" 88 * 89 * // Optional locale as the first argument can be used to get 90 * // locale-specific formatting of numbers. The precision and width can be 91 * // given to round and align the value. 92 * formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); 93 * // -> "e = +2,7183" 94 * 95 * // The '(' numeric flag may be used to format negative numbers with 96 * // parentheses rather than a minus sign. Group separators are 97 * // automatically inserted. 98 * formatter.format("Amount gained or lost since last statement: $ %(,.2f", 99 * balanceDelta); 100 * // -> "Amount gained or lost since last statement: $ (6,217.58)" 101 * </pre></blockquote> 102 * 103 * <p> Convenience methods for common formatting requests exist as illustrated 104 * by the following invocations: 105 * 106 * <blockquote><pre> 107 * // Writes a formatted string to System.out. 108 * System.out.format("Local time: %tT", Calendar.getInstance()); 109 * // -> "Local time: 13:34:18" 110 * 111 * // Writes formatted output to System.err. 112 * System.err.printf("Unable to open file '%1$s': %2$s", 113 * fileName, exception.getMessage()); 114 * // -> "Unable to open file 'food': No such file or directory" 115 * </pre></blockquote> 116 * 117 * <p> Like C's {@code sprintf(3)}, Strings may be formatted using the static 118 * method {@link String#format(String,Object...) String.format}: 119 * 120 * <blockquote><pre> 121 * // Format a string containing a date. 122 * import java.util.Calendar; 123 * import java.util.GregorianCalendar; 124 * import static java.util.Calendar.*; 125 * 126 * Calendar c = new GregorianCalendar(1995, MAY, 23); 127 * String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); 128 * // -> s == "Duke's Birthday: May 23, 1995" 129 * </pre></blockquote> 130 * 131 * <h3><a name="org">Organization</a></h3> 132 * 133 * <p> This specification is divided into two sections. The first section, <a 134 * href="#summary">Summary</a>, covers the basic formatting concepts. This 135 * section is intended for users who want to get started quickly and are 136 * familiar with formatted printing in other programming languages. The second 137 * section, <a href="#detail">Details</a>, covers the specific implementation 138 * details. It is intended for users who want more precise specification of 139 * formatting behavior. 140 * 141 * <h3><a name="summary">Summary</a></h3> 142 * 143 * <p> This section is intended to provide a brief overview of formatting 144 * concepts. For precise behavioral details, refer to the <a 145 * href="#detail">Details</a> section. 146 * 147 * <h4><a name="syntax">Format String Syntax</a></h4> 148 * 149 * <p> Every method which produces formatted output requires a <i>format 150 * string</i> and an <i>argument list</i>. The format string is a {@link 151 * String} which may contain fixed text and one or more embedded <i>format 152 * specifiers</i>. Consider the following example: 153 * 154 * <blockquote><pre> 155 * Calendar c = ...; 156 * String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); 157 * </pre></blockquote> 158 * 159 * This format string is the first argument to the {@code format} method. It 160 * contains three format specifiers "{@code %1$tm}", "{@code %1$te}", and 161 * "{@code %1$tY}" which indicate how the arguments should be processed and 162 * where they should be inserted in the text. The remaining portions of the 163 * format string are fixed text including {@code "Dukes Birthday: "} and any 164 * other spaces or punctuation. 165 * 166 * The argument list consists of all arguments passed to the method after the 167 * format string. In the above example, the argument list is of size one and 168 * consists of the {@link java.util.Calendar Calendar} object {@code c}. 169 * 170 * <ul> 171 * 172 * <li> The format specifiers for general, character, and numeric types have 173 * the following syntax: 174 * 175 * <blockquote><pre> 176 * %[argument_index$][flags][width][.precision]conversion 177 * </pre></blockquote> 178 * 179 * <p> The optional <i>argument_index</i> is a decimal integer indicating the 180 * position of the argument in the argument list. The first argument is 181 * referenced by "{@code 1$}", the second by "{@code 2$}", etc. 182 * 183 * <p> The optional <i>flags</i> is a set of characters that modify the output 184 * format. The set of valid flags depends on the conversion. 185 * 186 * <p> The optional <i>width</i> is a non-negative decimal integer indicating 187 * the minimum number of characters to be written to the output. 188 * 189 * <p> The optional <i>precision</i> is a non-negative decimal integer usually 190 * used to restrict the number of characters. The specific behavior depends on 191 * the conversion. 192 * 193 * <p> The required <i>conversion</i> is a character indicating how the 194 * argument should be formatted. The set of valid conversions for a given 195 * argument depends on the argument's data type. 196 * 197 * <li> The format specifiers for types which are used to represents dates and 198 * times have the following syntax: 199 * 200 * <blockquote><pre> 201 * %[argument_index$][flags][width]conversion 202 * </pre></blockquote> 203 * 204 * <p> The optional <i>argument_index</i>, <i>flags</i> and <i>width</i> are 205 * defined as above. 206 * 207 * <p> The required <i>conversion</i> is a two character sequence. The first 208 * character is {@code 't'} or {@code 'T'}. The second character indicates 209 * the format to be used. These characters are similar to but not completely 210 * identical to those defined by GNU {@code date} and POSIX 211 * {@code strftime(3c)}. 212 * 213 * <li> The format specifiers which do not correspond to arguments have the 214 * following syntax: 215 * 216 * <blockquote><pre> 217 * %[flags][width]conversion 218 * </pre></blockquote> 219 * 220 * <p> The optional <i>flags</i> and <i>width</i> is defined as above. 221 * 222 * <p> The required <i>conversion</i> is a character indicating content to be 223 * inserted in the output. 224 * 225 * </ul> 226 * 227 * <h4> Conversions </h4> 228 * 229 * <p> Conversions are divided into the following categories: 230 * 231 * <ol> 232 * 233 * <li> <b>General</b> - may be applied to any argument 234 * type 235 * 236 * <li> <b>Character</b> - may be applied to basic types which represent 237 * Unicode characters: {@code char}, {@link Character}, {@code byte}, {@link 238 * Byte}, {@code short}, and {@link Short}. This conversion may also be 239 * applied to the types {@code int} and {@link Integer} when {@link 240 * Character#isValidCodePoint} returns {@code true} 241 * 242 * <li> <b>Numeric</b> 243 * 244 * <ol> 245 * 246 * <li> <b>Integral</b> - may be applied to Java integral types: {@code byte}, 247 * {@link Byte}, {@code short}, {@link Short}, {@code int} and {@link 248 * Integer}, {@code long}, {@link Long}, and {@link java.math.BigInteger 249 * BigInteger} 250 * 251 * <li><b>Floating Point</b> - may be applied to Java floating-point types: 252 * {@code float}, {@link Float}, {@code double}, {@link Double}, and {@link 253 * java.math.BigDecimal BigDecimal} 254 * 255 * </ol> 256 * 257 * <li> <b>Date/Time</b> - may be applied to Java types which are capable of 258 * encoding a date or time: {@code long}, {@link Long}, {@link Calendar}, and 259 * {@link Date}. 260 * 261 * <li> <b>Percent</b> - produces a literal {@code '%'} 262 * (<tt>'\u0025'</tt>) 263 * 264 * <li> <b>Line Separator</b> - produces the platform-specific line separator 265 * 266 * </ol> 267 * 268 * <p> The following table summarizes the supported conversions. Conversions 269 * denoted by an upper-case character (i.e. {@code 'B'}, {@code 'H'}, 270 * {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'}, {@code 'G'}, 271 * {@code 'A'}, and {@code 'T'}) are the same as those for the corresponding 272 * lower-case conversion characters except that the result is converted to 273 * upper case according to the rules of the prevailing {@link java.util.Locale 274 * Locale}. The result is equivalent to the following invocation of {@link 275 * String#toUpperCase()} 276 * 277 * <pre> 278 * out.toUpperCase() </pre> 279 * 280 * <table cellpadding=5 summary="genConv"> 281 * 282 * <tr><th valign="bottom"> Conversion 283 * <th valign="bottom"> Argument Category 284 * <th valign="bottom"> Description 285 * 286 * <tr><td valign="top"> {@code 'b'}, {@code 'B'} 287 * <td valign="top"> general 288 * <td> If the argument <i>arg</i> is {@code null}, then the result is 289 * "{@code false}". If <i>arg</i> is a {@code boolean} or {@link 290 * Boolean}, then the result is the string returned by {@link 291 * String#valueOf(boolean) String.valueOf(arg)}. Otherwise, the result is 292 * "true". 293 * 294 * <tr><td valign="top"> {@code 'h'}, {@code 'H'} 295 * <td valign="top"> general 296 * <td> If the argument <i>arg</i> is {@code null}, then the result is 297 * "{@code null}". Otherwise, the result is obtained by invoking 298 * {@code Integer.toHexString(arg.hashCode())}. 299 * 300 * <tr><td valign="top"> {@code 's'}, {@code 'S'} 301 * <td valign="top"> general 302 * <td> If the argument <i>arg</i> is {@code null}, then the result is 303 * "{@code null}". If <i>arg</i> implements {@link Formattable}, then 304 * {@link Formattable#formatTo arg.formatTo} is invoked. Otherwise, the 305 * result is obtained by invoking {@code arg.toString()}. 306 * 307 * <tr><td valign="top">{@code 'c'}, {@code 'C'} 308 * <td valign="top"> character 309 * <td> The result is a Unicode character 310 * 311 * <tr><td valign="top">{@code 'd'} 312 * <td valign="top"> integral 313 * <td> The result is formatted as a decimal integer 314 * 315 * <tr><td valign="top">{@code 'o'} 316 * <td valign="top"> integral 317 * <td> The result is formatted as an octal integer 318 * 319 * <tr><td valign="top">{@code 'x'}, {@code 'X'} 320 * <td valign="top"> integral 321 * <td> The result is formatted as a hexadecimal integer 322 * 323 * <tr><td valign="top">{@code 'e'}, {@code 'E'} 324 * <td valign="top"> floating point 325 * <td> The result is formatted as a decimal number in computerized 326 * scientific notation 327 * 328 * <tr><td valign="top">{@code 'f'} 329 * <td valign="top"> floating point 330 * <td> The result is formatted as a decimal number 331 * 332 * <tr><td valign="top">{@code 'g'}, {@code 'G'} 333 * <td valign="top"> floating point 334 * <td> The result is formatted using computerized scientific notation or 335 * decimal format, depending on the precision and the value after rounding. 336 * 337 * <tr><td valign="top">{@code 'a'}, {@code 'A'} 338 * <td valign="top"> floating point 339 * <td> The result is formatted as a hexadecimal floating-point number with 340 * a significand and an exponent 341 * 342 * <tr><td valign="top">{@code 't'}, {@code 'T'} 343 * <td valign="top"> date/time 344 * <td> Prefix for date and time conversion characters. See <a 345 * href="#dt">Date/Time Conversions</a>. 346 * 347 * <tr><td valign="top">{@code '%'} 348 * <td valign="top"> percent 349 * <td> The result is a literal {@code '%'} (<tt>'\u0025'</tt>) 350 * 351 * <tr><td valign="top">{@code 'n'} 352 * <td valign="top"> line separator 353 * <td> The result is the platform-specific line separator 354 * 355 * </table> 356 * 357 * <p> Any characters not explicitly defined as conversions are illegal and are 358 * reserved for future extensions. 359 * 360 * <h4><a name="dt">Date/Time Conversions</a></h4> 361 * 362 * <p> The following date and time conversion suffix characters are defined for 363 * the {@code 't'} and {@code 'T'} conversions. The types are similar to but 364 * not completely identical to those defined by GNU {@code date} and POSIX 365 * {@code strftime(3c)}. Additional conversion types are provided to access 366 * Java-specific functionality (e.g. {@code 'L'} for milliseconds within the 367 * second). 368 * 369 * <p> The following conversion characters are used for formatting times: 370 * 371 * <table cellpadding=5 summary="time"> 372 * 373 * <tr><td valign="top"> {@code 'H'} 374 * <td> Hour of the day for the 24-hour clock, formatted as two digits with 375 * a leading zero as necessary i.e. {@code 00 - 23}. 376 * 377 * <tr><td valign="top">{@code 'I'} 378 * <td> Hour for the 12-hour clock, formatted as two digits with a leading 379 * zero as necessary, i.e. {@code 01 - 12}. 380 * 381 * <tr><td valign="top">{@code 'k'} 382 * <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}. 383 * 384 * <tr><td valign="top">{@code 'l'} 385 * <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}. 386 * 387 * <tr><td valign="top">{@code 'M'} 388 * <td> Minute within the hour formatted as two digits with a leading zero 389 * as necessary, i.e. {@code 00 - 59}. 390 * 391 * <tr><td valign="top">{@code 'S'} 392 * <td> Seconds within the minute, formatted as two digits with a leading 393 * zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special 394 * value required to support leap seconds). 395 * 396 * <tr><td valign="top">{@code 'L'} 397 * <td> Millisecond within the second formatted as three digits with 398 * leading zeros as necessary, i.e. {@code 000 - 999}. 399 * 400 * <tr><td valign="top">{@code 'N'} 401 * <td> Nanosecond within the second, formatted as nine digits with leading 402 * zeros as necessary, i.e. {@code 000000000 - 999999999}. 403 * 404 * <tr><td valign="top">{@code 'p'} 405 * <td> Locale-specific {@linkplain 406 * java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker 407 * in lower case, e.g."{@code am}" or "{@code pm}". Use of the conversion 408 * prefix {@code 'T'} forces this output to upper case. 409 * 410 * <tr><td valign="top">{@code 'z'} 411 * <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a> 412 * style numeric time zone offset from GMT, e.g. {@code -0800}. This 413 * value will be adjusted as necessary for Daylight Saving Time. For 414 * {@code long}, {@link Long}, and {@link Date} the time zone used is 415 * the {@linkplain TimeZone#getDefault() default time zone} for this 416 * instance of the Java virtual machine. 417 * 418 * <tr><td valign="top">{@code 'Z'} 419 * <td> A string representing the abbreviation for the time zone. This 420 * value will be adjusted as necessary for Daylight Saving Time. For 421 * {@code long}, {@link Long}, and {@link Date} the time zone used is 422 * the {@linkplain TimeZone#getDefault() default time zone} for this 423 * instance of the Java virtual machine. The Formatter's locale will 424 * supersede the locale of the argument (if any). 425 * 426 * <tr><td valign="top">{@code 's'} 427 * <td> Seconds since the beginning of the epoch starting at 1 January 1970 428 * {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to 429 * {@code Long.MAX_VALUE/1000}. 430 * 431 * <tr><td valign="top">{@code 'Q'} 432 * <td> Milliseconds since the beginning of the epoch starting at 1 January 433 * 1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to 434 * {@code Long.MAX_VALUE}. 435 * 436 * </table> 437 * 438 * <p> The following conversion characters are used for formatting dates: 439 * 440 * <table cellpadding=5 summary="date"> 441 * 442 * <tr><td valign="top">{@code 'B'} 443 * <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths 444 * full month name}, e.g. {@code "January"}, {@code "February"}. 445 * 446 * <tr><td valign="top">{@code 'b'} 447 * <td> Locale-specific {@linkplain 448 * java.text.DateFormatSymbols#getShortMonths abbreviated month name}, 449 * e.g. {@code "Jan"}, {@code "Feb"}. 450 * 451 * <tr><td valign="top">{@code 'h'} 452 * <td> Same as {@code 'b'}. 453 * 454 * <tr><td valign="top">{@code 'A'} 455 * <td> Locale-specific full name of the {@linkplain 456 * java.text.DateFormatSymbols#getWeekdays day of the week}, 457 * e.g. {@code "Sunday"}, {@code "Monday"} 458 * 459 * <tr><td valign="top">{@code 'a'} 460 * <td> Locale-specific short name of the {@linkplain 461 * java.text.DateFormatSymbols#getShortWeekdays day of the week}, 462 * e.g. {@code "Sun"}, {@code "Mon"} 463 * 464 * <tr><td valign="top">{@code 'C'} 465 * <td> Four-digit year divided by {@code 100}, formatted as two digits 466 * with leading zero as necessary, i.e. {@code 00 - 99} 467 * 468 * <tr><td valign="top">{@code 'Y'} 469 * <td> Year, formatted as at least four digits with leading zeros as 470 * necessary, e.g. {@code 0092} equals {@code 92} CE for the Gregorian 471 * calendar. 472 * 473 * <tr><td valign="top">{@code 'y'} 474 * <td> Last two digits of the year, formatted with leading zeros as 475 * necessary, i.e. {@code 00 - 99}. 476 * 477 * <tr><td valign="top">{@code 'j'} 478 * <td> Day of year, formatted as three digits with leading zeros as 479 * necessary, e.g. {@code 001 - 366} for the Gregorian calendar. 480 * 481 * <tr><td valign="top">{@code 'm'} 482 * <td> Month, formatted as two digits with leading zeros as necessary, 483 * i.e. {@code 01 - 13}. 484 * 485 * <tr><td valign="top">{@code 'd'} 486 * <td> Day of month, formatted as two digits with leading zeros as 487 * necessary, i.e. {@code 01 - 31} 488 * 489 * <tr><td valign="top">{@code 'e'} 490 * <td> Day of month, formatted as two digits, i.e. {@code 1 - 31}. 491 * 492 * </table> 493 * 494 * <p> The following conversion characters are used for formatting common 495 * date/time compositions. 496 * 497 * <table cellpadding=5 summary="composites"> 498 * 499 * <tr><td valign="top">{@code 'R'} 500 * <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"} 501 * 502 * <tr><td valign="top">{@code 'T'} 503 * <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}. 504 * 505 * <tr><td valign="top">{@code 'r'} 506 * <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS %Tp"}. 507 * The location of the morning or afternoon marker ({@code '%Tp'}) may be 508 * locale-dependent. 509 * 510 * <tr><td valign="top">{@code 'D'} 511 * <td> Date formatted as {@code "%tm/%td/%ty"}. 512 * 513 * <tr><td valign="top">{@code 'F'} 514 * <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> 515 * complete date formatted as {@code "%tY-%tm-%td"}. 516 * 517 * <tr><td valign="top">{@code 'c'} 518 * <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"}, 519 * e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}. 520 * 521 * </table> 522 * 523 * <p> Any characters not explicitly defined as date/time conversion suffixes 524 * are illegal and are reserved for future extensions. 525 * 526 * <h4> Flags </h4> 527 * 528 * <p> The following table summarizes the supported flags. <i>y</i> means the 529 * flag is supported for the indicated argument types. 530 * 531 * <table cellpadding=5 summary="genConv"> 532 * 533 * <tr><th valign="bottom"> Flag <th valign="bottom"> General 534 * <th valign="bottom"> Character <th valign="bottom"> Integral 535 * <th valign="bottom"> Floating Point 536 * <th valign="bottom"> Date/Time 537 * <th valign="bottom"> Description 538 * 539 * <tr><td> '-' <td align="center" valign="top"> y 540 * <td align="center" valign="top"> y 541 * <td align="center" valign="top"> y 542 * <td align="center" valign="top"> y 543 * <td align="center" valign="top"> y 544 * <td> The result will be left-justified. 545 * 546 * <tr><td> '#' <td align="center" valign="top"> y<sup>1</sup> 547 * <td align="center" valign="top"> - 548 * <td align="center" valign="top"> y<sup>3</sup> 549 * <td align="center" valign="top"> y 550 * <td align="center" valign="top"> - 551 * <td> The result should use a conversion-dependent alternate form 552 * 553 * <tr><td> '+' <td align="center" valign="top"> - 554 * <td align="center" valign="top"> - 555 * <td align="center" valign="top"> y<sup>4</sup> 556 * <td align="center" valign="top"> y 557 * <td align="center" valign="top"> - 558 * <td> The result will always include a sign 559 * 560 * <tr><td> ' ' <td align="center" valign="top"> - 561 * <td align="center" valign="top"> - 562 * <td align="center" valign="top"> y<sup>4</sup> 563 * <td align="center" valign="top"> y 564 * <td align="center" valign="top"> - 565 * <td> The result will include a leading space for positive values 566 * 567 * <tr><td> '0' <td align="center" valign="top"> - 568 * <td align="center" valign="top"> - 569 * <td align="center" valign="top"> y 570 * <td align="center" valign="top"> y 571 * <td align="center" valign="top"> - 572 * <td> The result will be zero-padded 573 * 574 * <tr><td> ',' <td align="center" valign="top"> - 575 * <td align="center" valign="top"> - 576 * <td align="center" valign="top"> y<sup>2</sup> 577 * <td align="center" valign="top"> y<sup>5</sup> 578 * <td align="center" valign="top"> - 579 * <td> The result will include locale-specific {@linkplain 580 * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separators} 581 * 582 * <tr><td> '(' <td align="center" valign="top"> - 583 * <td align="center" valign="top"> - 584 * <td align="center" valign="top"> y<sup>4</sup> 585 * <td align="center" valign="top"> y<sup>5</sup> 586 * <td align="center"> - 587 * <td> The result will enclose negative numbers in parentheses 588 * 589 * </table> 590 * 591 * <p> <sup>1</sup> Depends on the definition of {@link Formattable}. 592 * 593 * <p> <sup>2</sup> For {@code 'd'} conversion only. 594 * 595 * <p> <sup>3</sup> For {@code 'o'}, {@code 'x'}, and {@code 'X'} 596 * conversions only. 597 * 598 * <p> <sup>4</sup> For {@code 'd'}, {@code 'o'}, {@code 'x'}, and 599 * {@code 'X'} conversions applied to {@link java.math.BigInteger BigInteger} 600 * or {@code 'd'} applied to {@code byte}, {@link Byte}, {@code short}, {@link 601 * Short}, {@code int} and {@link Integer}, {@code long}, and {@link Long}. 602 * 603 * <p> <sup>5</sup> For {@code 'e'}, {@code 'E'}, {@code 'f'}, 604 * {@code 'g'}, and {@code 'G'} conversions only. 605 * 606 * <p> Any characters not explicitly defined as flags are illegal and are 607 * reserved for future extensions. 608 * 609 * <h4> Width </h4> 610 * 611 * <p> The width is the minimum number of characters to be written to the 612 * output. For the line separator conversion, width is not applicable; if it 613 * is provided, an exception will be thrown. 614 * 615 * <h4> Precision </h4> 616 * 617 * <p> For general argument types, the precision is the maximum number of 618 * characters to be written to the output. 619 * 620 * <p> For the floating-point conversions {@code 'e'}, {@code 'E'}, and 621 * {@code 'f'} the precision is the number of digits after the decimal 622 * separator. If the conversion is {@code 'g'} or {@code 'G'}, then the 623 * precision is the total number of digits in the resulting magnitude after 624 * rounding. If the conversion is {@code 'a'} or {@code 'A'}, then the 625 * precision must not be specified. 626 * 627 * <p> For character, integral, and date/time argument types and the percent 628 * and line separator conversions, the precision is not applicable; if a 629 * precision is provided, an exception will be thrown. 630 * 631 * <h4> Argument Index </h4> 632 * 633 * <p> The argument index is a decimal integer indicating the position of the 634 * argument in the argument list. The first argument is referenced by 635 * "{@code 1$}", the second by "{@code 2$}", etc. 636 * 637 * <p> Another way to reference arguments by position is to use the 638 * {@code '<'} (<tt>'\u003c'</tt>) flag, which causes the argument for 639 * the previous format specifier to be re-used. For example, the following two 640 * statements would produce identical strings: 641 * 642 * <blockquote><pre> 643 * Calendar c = ...; 644 * String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); 645 * 646 * String s2 = String.format("Duke's Birthday: %1$tm %<te,%<tY", c); 647 * </pre></blockquote> 648 * 649 * <hr> 650 * <h3><a name="detail">Details</a></h3> 651 * 652 * <p> This section is intended to provide behavioral details for formatting, 653 * including conditions and exceptions, supported data types, localization, and 654 * interactions between flags, conversions, and data types. For an overview of 655 * formatting concepts, refer to the <a href="#summary">Summary</a> 656 * 657 * <p> Any characters not explicitly defined as conversions, date/time 658 * conversion suffixes, or flags are illegal and are reserved for 659 * future extensions. Use of such a character in a format string will 660 * cause an {@link UnknownFormatConversionException} or {@link 661 * UnknownFormatFlagsException} to be thrown. 662 * 663 * <p> If the format specifier contains a width or precision with an invalid 664 * value or which is otherwise unsupported, then a {@link 665 * IllegalFormatWidthException} or {@link IllegalFormatPrecisionException} 666 * respectively will be thrown. 667 * 668 * <p> If a format specifier contains a conversion character that is not 669 * applicable to the corresponding argument, then an {@link 670 * IllegalFormatConversionException} will be thrown. 671 * 672 * <p> All specified exceptions may be thrown by any of the {@code format} 673 * methods of {@code Formatter} as well as by any {@code format} convenience 674 * methods such as {@link String#format(String,Object...) String.format} and 675 * {@link java.io.PrintStream#printf(String,Object...) PrintStream.printf}. 676 * 677 * <p> Conversions denoted by an upper-case character (i.e. {@code 'B'}, 678 * {@code 'H'}, {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'}, 679 * {@code 'G'}, {@code 'A'}, and {@code 'T'}) are the same as those for the 680 * corresponding lower-case conversion characters except that the result is 681 * converted to upper case according to the rules of the prevailing {@link 682 * java.util.Locale Locale}. The result is equivalent to the following 683 * invocation of {@link String#toUpperCase()} 684 * 685 * <pre> 686 * out.toUpperCase() </pre> 687 * 688 * <h4><a name="dgen">General</a></h4> 689 * 690 * <p> The following general conversions may be applied to any argument type: 691 * 692 * <table cellpadding=5 summary="dgConv"> 693 * 694 * <tr><td valign="top"> {@code 'b'} 695 * <td valign="top"> <tt>'\u0062'</tt> 696 * <td> Produces either "{@code true}" or "{@code false}" as returned by 697 * {@link Boolean#toString(boolean)}. 698 * 699 * <p> If the argument is {@code null}, then the result is 700 * "{@code false}". If the argument is a {@code boolean} or {@link 701 * Boolean}, then the result is the string returned by {@link 702 * String#valueOf(boolean) String.valueOf()}. Otherwise, the result is 703 * "{@code true}". 704 * 705 * <p> If the {@code '#'} flag is given, then a {@link 706 * FormatFlagsConversionMismatchException} will be thrown. 707 * 708 * <tr><td valign="top"> {@code 'B'} 709 * <td valign="top"> <tt>'\u0042'</tt> 710 * <td> The upper-case variant of {@code 'b'}. 711 * 712 * <tr><td valign="top"> {@code 'h'} 713 * <td valign="top"> <tt>'\u0068'</tt> 714 * <td> Produces a string representing the hash code value of the object. 715 * 716 * <p> If the argument, <i>arg</i> is {@code null}, then the 717 * result is "{@code null}". Otherwise, the result is obtained 718 * by invoking {@code Integer.toHexString(arg.hashCode())}. 719 * 720 * <p> If the {@code '#'} flag is given, then a {@link 721 * FormatFlagsConversionMismatchException} will be thrown. 722 * 723 * <tr><td valign="top"> {@code 'H'} 724 * <td valign="top"> <tt>'\u0048'</tt> 725 * <td> The upper-case variant of {@code 'h'}. 726 * 727 * <tr><td valign="top"> {@code 's'} 728 * <td valign="top"> <tt>'\u0073'</tt> 729 * <td> Produces a string. 730 * 731 * <p> If the argument is {@code null}, then the result is 732 * "{@code null}". If the argument implements {@link Formattable}, then 733 * its {@link Formattable#formatTo formatTo} method is invoked. 734 * Otherwise, the result is obtained by invoking the argument's 735 * {@code toString()} method. 736 * 737 * <p> If the {@code '#'} flag is given and the argument is not a {@link 738 * Formattable} , then a {@link FormatFlagsConversionMismatchException} 739 * will be thrown. 740 * 741 * <tr><td valign="top"> {@code 'S'} 742 * <td valign="top"> <tt>'\u0053'</tt> 743 * <td> The upper-case variant of {@code 's'}. 744 * 745 * </table> 746 * 747 * <p> The following <a name="dFlags">flags</a> apply to general conversions: 748 * 749 * <table cellpadding=5 summary="dFlags"> 750 * 751 * <tr><td valign="top"> {@code '-'} 752 * <td valign="top"> <tt>'\u002d'</tt> 753 * <td> Left justifies the output. Spaces (<tt>'\u0020'</tt>) will be 754 * added at the end of the converted value as required to fill the minimum 755 * width of the field. If the width is not provided, then a {@link 756 * MissingFormatWidthException} will be thrown. If this flag is not given 757 * then the output will be right-justified. 758 * 759 * <tr><td valign="top"> {@code '#'} 760 * <td valign="top"> <tt>'\u0023'</tt> 761 * <td> Requires the output use an alternate form. The definition of the 762 * form is specified by the conversion. 763 * 764 * </table> 765 * 766 * <p> The <a name="genWidth">width</a> is the minimum number of characters to 767 * be written to the 768 * output. If the length of the converted value is less than the width then 769 * the output will be padded by <tt>' '</tt> (<tt>'\u0020'</tt>) 770 * until the total number of characters equals the width. The padding is on 771 * the left by default. If the {@code '-'} flag is given, then the padding 772 * will be on the right. If the width is not specified then there is no 773 * minimum. 774 * 775 * <p> The precision is the maximum number of characters to be written to the 776 * output. The precision is applied before the width, thus the output will be 777 * truncated to {@code precision} characters even if the width is greater than 778 * the precision. If the precision is not specified then there is no explicit 779 * limit on the number of characters. 780 * 781 * <h4><a name="dchar">Character</a></h4> 782 * 783 * This conversion may be applied to {@code char} and {@link Character}. It 784 * may also be applied to the types {@code byte}, {@link Byte}, 785 * {@code short}, and {@link Short}, {@code int} and {@link Integer} when 786 * {@link Character#isValidCodePoint} returns {@code true}. If it returns 787 * {@code false} then an {@link IllegalFormatCodePointException} will be 788 * thrown. 789 * 790 * <table cellpadding=5 summary="charConv"> 791 * 792 * <tr><td valign="top"> {@code 'c'} 793 * <td valign="top"> <tt>'\u0063'</tt> 794 * <td> Formats the argument as a Unicode character as described in <a 795 * href="../lang/Character.html#unicode">Unicode Character 796 * Representation</a>. This may be more than one 16-bit {@code char} in 797 * the case where the argument represents a supplementary character. 798 * 799 * <p> If the {@code '#'} flag is given, then a {@link 800 * FormatFlagsConversionMismatchException} will be thrown. 801 * 802 * <tr><td valign="top"> {@code 'C'} 803 * <td valign="top"> <tt>'\u0043'</tt> 804 * <td> The upper-case variant of {@code 'c'}. 805 * 806 * </table> 807 * 808 * <p> The {@code '-'} flag defined for <a href="#dFlags">General 809 * conversions</a> applies. If the {@code '#'} flag is given, then a {@link 810 * FormatFlagsConversionMismatchException} will be thrown. 811 * 812 * <p> The width is defined as for <a href="#genWidth">General conversions</a>. 813 * 814 * <p> The precision is not applicable. If the precision is specified then an 815 * {@link IllegalFormatPrecisionException} will be thrown. 816 * 817 * <h4><a name="dnum">Numeric</a></h4> 818 * 819 * <p> Numeric conversions are divided into the following categories: 820 * 821 * <ol> 822 * 823 * <li> <a href="#dnint"><b>Byte, Short, Integer, and Long</b></a> 824 * 825 * <li> <a href="#dnbint"><b>BigInteger</b></a> 826 * 827 * <li> <a href="#dndec"><b>Float and Double</b></a> 828 * 829 * <li> <a href="#dnbdec"><b>BigDecimal</b></a> 830 * 831 * </ol> 832 * 833 * <p> Numeric types will be formatted according to the following algorithm: 834 * 835 * <p><b><a name="l10n algorithm"> Number Localization Algorithm</a></b> 836 * 837 * <p> After digits are obtained for the integer part, fractional part, and 838 * exponent (as appropriate for the data type), the following transformation 839 * is applied: 840 * 841 * <ol> 842 * 843 * <li> Each digit character <i>d</i> in the string is replaced by a 844 * locale-specific digit computed relative to the current locale's 845 * {@linkplain java.text.DecimalFormatSymbols#getZeroDigit() zero digit} 846 * <i>z</i>; that is <i>d - </i> {@code '0'} 847 * <i> + z</i>. 848 * 849 * <li> If a decimal separator is present, a locale-specific {@linkplain 850 * java.text.DecimalFormatSymbols#getDecimalSeparator decimal separator} is 851 * substituted. 852 * 853 * <li> If the {@code ','} (<tt>'\u002c'</tt>) 854 * <a name="l10n group">flag</a> is given, then the locale-specific {@linkplain 855 * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is 856 * inserted by scanning the integer part of the string from least significant 857 * to most significant digits and inserting a separator at intervals defined by 858 * the locale's {@linkplain java.text.DecimalFormat#getGroupingSize() grouping 859 * size}. 860 * 861 * <li> If the {@code '0'} flag is given, then the locale-specific {@linkplain 862 * java.text.DecimalFormatSymbols#getZeroDigit() zero digits} are inserted 863 * after the sign character, if any, and before the first non-zero digit, until 864 * the length of the string is equal to the requested field width. 865 * 866 * <li> If the value is negative and the {@code '('} flag is given, then a 867 * {@code '('} (<tt>'\u0028'</tt>) is prepended and a {@code ')'} 868 * (<tt>'\u0029'</tt>) is appended. 869 * 870 * <li> If the value is negative (or floating-point negative zero) and 871 * {@code '('} flag is not given, then a {@code '-'} (<tt>'\u002d'</tt>) 872 * is prepended. 873 * 874 * <li> If the {@code '+'} flag is given and the value is positive or zero (or 875 * floating-point positive zero), then a {@code '+'} (<tt>'\u002b'</tt>) 876 * will be prepended. 877 * 878 * </ol> 879 * 880 * <p> If the value is NaN or positive infinity the literal strings "NaN" or 881 * "Infinity" respectively, will be output. If the value is negative infinity, 882 * then the output will be "(Infinity)" if the {@code '('} flag is given 883 * otherwise the output will be "-Infinity". These values are not localized. 884 * 885 * <p><a name="dnint"><b> Byte, Short, Integer, and Long </b></a> 886 * 887 * <p> The following conversions may be applied to {@code byte}, {@link Byte}, 888 * {@code short}, {@link Short}, {@code int} and {@link Integer}, 889 * {@code long}, and {@link Long}. 890 * 891 * <table cellpadding=5 summary="IntConv"> 892 * 893 * <tr><td valign="top"> {@code 'd'} 894 * <td valign="top"> <tt>'\u0054'</tt> 895 * <td> Formats the argument as a decimal integer. The <a 896 * href="#l10n algorithm">localization algorithm</a> is applied. 897 * 898 * <p> If the {@code '0'} flag is given and the value is negative, then 899 * the zero padding will occur after the sign. 900 * 901 * <p> If the {@code '#'} flag is given then a {@link 902 * FormatFlagsConversionMismatchException} will be thrown. 903 * 904 * <tr><td valign="top"> {@code 'o'} 905 * <td valign="top"> <tt>'\u006f'</tt> 906 * <td> Formats the argument as an integer in base eight. No localization 907 * is applied. 908 * 909 * <p> If <i>x</i> is negative then the result will be an unsigned value 910 * generated by adding 2<sup>n</sup> to the value where {@code n} is the 911 * number of bits in the type as returned by the static {@code SIZE} field 912 * in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short}, 913 * {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long} 914 * classes as appropriate. 915 * 916 * <p> If the {@code '#'} flag is given then the output will always begin 917 * with the radix indicator {@code '0'}. 918 * 919 * <p> If the {@code '0'} flag is given then the output will be padded 920 * with leading zeros to the field width following any indication of sign. 921 * 922 * <p> If {@code '('}, {@code '+'}, '  ', or {@code ','} flags 923 * are given then a {@link FormatFlagsConversionMismatchException} will be 924 * thrown. 925 * 926 * <tr><td valign="top"> {@code 'x'} 927 * <td valign="top"> <tt>'\u0078'</tt> 928 * <td> Formats the argument as an integer in base sixteen. No 929 * localization is applied. 930 * 931 * <p> If <i>x</i> is negative then the result will be an unsigned value 932 * generated by adding 2<sup>n</sup> to the value where {@code n} is the 933 * number of bits in the type as returned by the static {@code SIZE} field 934 * in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short}, 935 * {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long} 936 * classes as appropriate. 937 * 938 * <p> If the {@code '#'} flag is given then the output will always begin 939 * with the radix indicator {@code "0x"}. 940 * 941 * <p> If the {@code '0'} flag is given then the output will be padded to 942 * the field width with leading zeros after the radix indicator or sign (if 943 * present). 944 * 945 * <p> If {@code '('}, <tt>' '</tt>, {@code '+'}, or 946 * {@code ','} flags are given then a {@link 947 * FormatFlagsConversionMismatchException} will be thrown. 948 * 949 * <tr><td valign="top"> {@code 'X'} 950 * <td valign="top"> <tt>'\u0058'</tt> 951 * <td> The upper-case variant of {@code 'x'}. The entire string 952 * representing the number will be converted to {@linkplain 953 * String#toUpperCase upper case} including the {@code 'x'} (if any) and 954 * all hexadecimal digits {@code 'a'} - {@code 'f'} 955 * (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>). 956 * 957 * </table> 958 * 959 * <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and 960 * both the {@code '#'} and the {@code '0'} flags are given, then result will 961 * contain the radix indicator ({@code '0'} for octal and {@code "0x"} or 962 * {@code "0X"} for hexadecimal), some number of zeros (based on the width), 963 * and the value. 964 * 965 * <p> If the {@code '-'} flag is not given, then the space padding will occur 966 * before the sign. 967 * 968 * <p> The following <a name="intFlags">flags</a> apply to numeric integral 969 * conversions: 970 * 971 * <table cellpadding=5 summary="intFlags"> 972 * 973 * <tr><td valign="top"> {@code '+'} 974 * <td valign="top"> <tt>'\u002b'</tt> 975 * <td> Requires the output to include a positive sign for all positive 976 * numbers. If this flag is not given then only negative values will 977 * include a sign. 978 * 979 * <p> If both the {@code '+'} and <tt>' '</tt> flags are given 980 * then an {@link IllegalFormatFlagsException} will be thrown. 981 * 982 * <tr><td valign="top"> <tt>' '</tt> 983 * <td valign="top"> <tt>'\u0020'</tt> 984 * <td> Requires the output to include a single extra space 985 * (<tt>'\u0020'</tt>) for non-negative values. 986 * 987 * <p> If both the {@code '+'} and <tt>' '</tt> flags are given 988 * then an {@link IllegalFormatFlagsException} will be thrown. 989 * 990 * <tr><td valign="top"> {@code '0'} 991 * <td valign="top"> <tt>'\u0030'</tt> 992 * <td> Requires the output to be padded with leading {@linkplain 993 * java.text.DecimalFormatSymbols#getZeroDigit zeros} to the minimum field 994 * width following any sign or radix indicator except when converting NaN 995 * or infinity. If the width is not provided, then a {@link 996 * MissingFormatWidthException} will be thrown. 997 * 998 * <p> If both the {@code '-'} and {@code '0'} flags are given then an 999 * {@link IllegalFormatFlagsException} will be thrown. 1000 * 1001 * <tr><td valign="top"> {@code ','} 1002 * <td valign="top"> <tt>'\u002c'</tt> 1003 * <td> Requires the output to include the locale-specific {@linkplain 1004 * java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as 1005 * described in the <a href="#l10n group">"group" section</a> of the 1006 * localization algorithm. 1007 * 1008 * <tr><td valign="top"> {@code '('} 1009 * <td valign="top"> <tt>'\u0028'</tt> 1010 * <td> Requires the output to prepend a {@code '('} 1011 * (<tt>'\u0028'</tt>) and append a {@code ')'} 1012 * (<tt>'\u0029'</tt>) to negative values. 1013 * 1014 * </table> 1015 * 1016 * <p> If no <a name="intdFlags">flags</a> are given the default formatting is 1017 * as follows: 1018 * 1019 * <ul> 1020 * 1021 * <li> The output is right-justified within the {@code width} 1022 * 1023 * <li> Negative numbers begin with a {@code '-'} (<tt>'\u002d'</tt>) 1024 * 1025 * <li> Positive numbers and zero do not include a sign or extra leading 1026 * space 1027 * 1028 * <li> No grouping separators are included 1029 * 1030 * </ul> 1031 * 1032 * <p> The <a name="intWidth">width</a> is the minimum number of characters to 1033 * be written to the output. This includes any signs, digits, grouping 1034 * separators, radix indicator, and parentheses. If the length of the 1035 * converted value is less than the width then the output will be padded by 1036 * spaces (<tt>'\u0020'</tt>) until the total number of characters equals 1037 * width. The padding is on the left by default. If {@code '-'} flag is 1038 * given then the padding will be on the right. If width is not specified then 1039 * there is no minimum. 1040 * 1041 * <p> The precision is not applicable. If precision is specified then an 1042 * {@link IllegalFormatPrecisionException} will be thrown. 1043 * 1044 * <p><a name="dnbint"><b> BigInteger </b></a> 1045 * 1046 * <p> The following conversions may be applied to {@link 1047 * java.math.BigInteger}. 1048 * 1049 * <table cellpadding=5 summary="BIntConv"> 1050 * 1051 * <tr><td valign="top"> {@code 'd'} 1052 * <td valign="top"> <tt>'\u0054'</tt> 1053 * <td> Requires the output to be formatted as a decimal integer. The <a 1054 * href="#l10n algorithm">localization algorithm</a> is applied. 1055 * 1056 * <p> If the {@code '#'} flag is given {@link 1057 * FormatFlagsConversionMismatchException} will be thrown. 1058 * 1059 * <tr><td valign="top"> {@code 'o'} 1060 * <td valign="top"> <tt>'\u006f'</tt> 1061 * <td> Requires the output to be formatted as an integer in base eight. 1062 * No localization is applied. 1063 * 1064 * <p> If <i>x</i> is negative then the result will be a signed value 1065 * beginning with {@code '-'} (<tt>'\u002d'</tt>). Signed output is 1066 * allowed for this type because unlike the primitive types it is not 1067 * possible to create an unsigned equivalent without assuming an explicit 1068 * data-type size. 1069 * 1070 * <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given 1071 * then the result will begin with {@code '+'} (<tt>'\u002b'</tt>). 1072 * 1073 * <p> If the {@code '#'} flag is given then the output will always begin 1074 * with {@code '0'} prefix. 1075 * 1076 * <p> If the {@code '0'} flag is given then the output will be padded 1077 * with leading zeros to the field width following any indication of sign. 1078 * 1079 * <p> If the {@code ','} flag is given then a {@link 1080 * FormatFlagsConversionMismatchException} will be thrown. 1081 * 1082 * <tr><td valign="top"> {@code 'x'} 1083 * <td valign="top"> <tt>'\u0078'</tt> 1084 * <td> Requires the output to be formatted as an integer in base 1085 * sixteen. No localization is applied. 1086 * 1087 * <p> If <i>x</i> is negative then the result will be a signed value 1088 * beginning with {@code '-'} (<tt>'\u002d'</tt>). Signed output is 1089 * allowed for this type because unlike the primitive types it is not 1090 * possible to create an unsigned equivalent without assuming an explicit 1091 * data-type size. 1092 * 1093 * <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given 1094 * then the result will begin with {@code '+'} (<tt>'\u002b'</tt>). 1095 * 1096 * <p> If the {@code '#'} flag is given then the output will always begin 1097 * with the radix indicator {@code "0x"}. 1098 * 1099 * <p> If the {@code '0'} flag is given then the output will be padded to 1100 * the field width with leading zeros after the radix indicator or sign (if 1101 * present). 1102 * 1103 * <p> If the {@code ','} flag is given then a {@link 1104 * FormatFlagsConversionMismatchException} will be thrown. 1105 * 1106 * <tr><td valign="top"> {@code 'X'} 1107 * <td valign="top"> <tt>'\u0058'</tt> 1108 * <td> The upper-case variant of {@code 'x'}. The entire string 1109 * representing the number will be converted to {@linkplain 1110 * String#toUpperCase upper case} including the {@code 'x'} (if any) and 1111 * all hexadecimal digits {@code 'a'} - {@code 'f'} 1112 * (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>). 1113 * 1114 * </table> 1115 * 1116 * <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and 1117 * both the {@code '#'} and the {@code '0'} flags are given, then result will 1118 * contain the base indicator ({@code '0'} for octal and {@code "0x"} or 1119 * {@code "0X"} for hexadecimal), some number of zeros (based on the width), 1120 * and the value. 1121 * 1122 * <p> If the {@code '0'} flag is given and the value is negative, then the 1123 * zero padding will occur after the sign. 1124 * 1125 * <p> If the {@code '-'} flag is not given, then the space padding will occur 1126 * before the sign. 1127 * 1128 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and 1129 * Long apply. The <a href="#intdFlags">default behavior</a> when no flags are 1130 * given is the same as for Byte, Short, Integer, and Long. 1131 * 1132 * <p> The specification of <a href="#intWidth">width</a> is the same as 1133 * defined for Byte, Short, Integer, and Long. 1134 * 1135 * <p> The precision is not applicable. If precision is specified then an 1136 * {@link IllegalFormatPrecisionException} will be thrown. 1137 * 1138 * <p><a name="dndec"><b> Float and Double</b></a> 1139 * 1140 * <p> The following conversions may be applied to {@code float}, {@link 1141 * Float}, {@code double} and {@link Double}. 1142 * 1143 * <table cellpadding=5 summary="floatConv"> 1144 * 1145 * <tr><td valign="top"> {@code 'e'} 1146 * <td valign="top"> <tt>'\u0065'</tt> 1147 * <td> Requires the output to be formatted using <a 1148 * name="scientific">computerized scientific notation</a>. The <a 1149 * href="#l10n algorithm">localization algorithm</a> is applied. 1150 * 1151 * <p> The formatting of the magnitude <i>m</i> depends upon its value. 1152 * 1153 * <p> If <i>m</i> is NaN or infinite, the literal strings "NaN" or 1154 * "Infinity", respectively, will be output. These values are not 1155 * localized. 1156 * 1157 * <p> If <i>m</i> is positive-zero or negative-zero, then the exponent 1158 * will be {@code "+00"}. 1159 * 1160 * <p> Otherwise, the result is a string that represents the sign and 1161 * magnitude (absolute value) of the argument. The formatting of the sign 1162 * is described in the <a href="#l10n algorithm">localization 1163 * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its 1164 * value. 1165 * 1166 * <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup> 1167 * <= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the 1168 * mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so 1169 * that 1 <= <i>a</i> < 10. The magnitude is then represented as the 1170 * integer part of <i>a</i>, as a single decimal digit, followed by the 1171 * decimal separator followed by decimal digits representing the fractional 1172 * part of <i>a</i>, followed by the lower-case locale-specific {@linkplain 1173 * java.text.DecimalFormatSymbols#getExponentSeparator exponent separator} 1174 * (e.g. {@code 'e'}), followed by the sign of the exponent, followed 1175 * by a representation of <i>n</i> as a decimal integer, as produced by the 1176 * method {@link Long#toString(long, int)}, and zero-padded to include at 1177 * least two digits. 1178 * 1179 * <p> The number of digits in the result for the fractional part of 1180 * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not 1181 * specified then the default value is {@code 6}. If the precision is less 1182 * than the number of digits which would appear after the decimal point in 1183 * the string returned by {@link Float#toString(float)} or {@link 1184 * Double#toString(double)} respectively, then the value will be rounded 1185 * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up 1186 * algorithm}. Otherwise, zeros may be appended to reach the precision. 1187 * For a canonical representation of the value, use {@link 1188 * Float#toString(float)} or {@link Double#toString(double)} as 1189 * appropriate. 1190 * 1191 * <p>If the {@code ','} flag is given, then an {@link 1192 * FormatFlagsConversionMismatchException} will be thrown. 1193 * 1194 * <tr><td valign="top"> {@code 'E'} 1195 * <td valign="top"> <tt>'\u0045'</tt> 1196 * <td> The upper-case variant of {@code 'e'}. The exponent symbol 1197 * will be the upper-case locale-specific {@linkplain 1198 * java.text.DecimalFormatSymbols#getExponentSeparator exponent separator} 1199 * (e.g. {@code 'E'}). 1200 * 1201 * <tr><td valign="top"> {@code 'g'} 1202 * <td valign="top"> <tt>'\u0067'</tt> 1203 * <td> Requires the output to be formatted in general scientific notation 1204 * as described below. The <a href="#l10n algorithm">localization 1205 * algorithm</a> is applied. 1206 * 1207 * <p> After rounding for the precision, the formatting of the resulting 1208 * magnitude <i>m</i> depends on its value. 1209 * 1210 * <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less 1211 * than 10<sup>precision</sup> then it is represented in <i><a 1212 * href="#decimal">decimal format</a></i>. 1213 * 1214 * <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to 1215 * 10<sup>precision</sup>, then it is represented in <i><a 1216 * href="#scientific">computerized scientific notation</a></i>. 1217 * 1218 * <p> The total number of significant digits in <i>m</i> is equal to the 1219 * precision. If the precision is not specified, then the default value is 1220 * {@code 6}. If the precision is {@code 0}, then it is taken to be 1221 * {@code 1}. 1222 * 1223 * <p> If the {@code '#'} flag is given then an {@link 1224 * FormatFlagsConversionMismatchException} will be thrown. 1225 * 1226 * <tr><td valign="top"> {@code 'G'} 1227 * <td valign="top"> <tt>'\u0047'</tt> 1228 * <td> The upper-case variant of {@code 'g'}. 1229 * 1230 * <tr><td valign="top"> {@code 'f'} 1231 * <td valign="top"> <tt>'\u0066'</tt> 1232 * <td> Requires the output to be formatted using <a name="decimal">decimal 1233 * format</a>. The <a href="#l10n algorithm">localization algorithm</a> is 1234 * applied. 1235 * 1236 * <p> The result is a string that represents the sign and magnitude 1237 * (absolute value) of the argument. The formatting of the sign is 1238 * described in the <a href="#l10n algorithm">localization 1239 * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its 1240 * value. 1241 * 1242 * <p> If <i>m</i> NaN or infinite, the literal strings "NaN" or 1243 * "Infinity", respectively, will be output. These values are not 1244 * localized. 1245 * 1246 * <p> The magnitude is formatted as the integer part of <i>m</i>, with no 1247 * leading zeroes, followed by the decimal separator followed by one or 1248 * more decimal digits representing the fractional part of <i>m</i>. 1249 * 1250 * <p> The number of digits in the result for the fractional part of 1251 * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not 1252 * specified then the default value is {@code 6}. If the precision is less 1253 * than the number of digits which would appear after the decimal point in 1254 * the string returned by {@link Float#toString(float)} or {@link 1255 * Double#toString(double)} respectively, then the value will be rounded 1256 * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up 1257 * algorithm}. Otherwise, zeros may be appended to reach the precision. 1258 * For a canonical representation of the value, use {@link 1259 * Float#toString(float)} or {@link Double#toString(double)} as 1260 * appropriate. 1261 * 1262 * <tr><td valign="top"> {@code 'a'} 1263 * <td valign="top"> <tt>'\u0061'</tt> 1264 * <td> Requires the output to be formatted in hexadecimal exponential 1265 * form. No localization is applied. 1266 * 1267 * <p> The result is a string that represents the sign and magnitude 1268 * (absolute value) of the argument <i>x</i>. 1269 * 1270 * <p> If <i>x</i> is negative or a negative-zero value then the result 1271 * will begin with {@code '-'} (<tt>'\u002d'</tt>). 1272 * 1273 * <p> If <i>x</i> is positive or a positive-zero value and the 1274 * {@code '+'} flag is given then the result will begin with {@code '+'} 1275 * (<tt>'\u002b'</tt>). 1276 * 1277 * <p> The formatting of the magnitude <i>m</i> depends upon its value. 1278 * 1279 * <ul> 1280 * 1281 * <li> If the value is NaN or infinite, the literal strings "NaN" or 1282 * "Infinity", respectively, will be output. 1283 * 1284 * <li> If <i>m</i> is zero then it is represented by the string 1285 * {@code "0x0.0p0"}. 1286 * 1287 * <li> If <i>m</i> is a {@code double} value with a normalized 1288 * representation then substrings are used to represent the significand and 1289 * exponent fields. The significand is represented by the characters 1290 * {@code "0x1."} followed by the hexadecimal representation of the rest 1291 * of the significand as a fraction. The exponent is represented by 1292 * {@code 'p'} (<tt>'\u0070'</tt>) followed by a decimal string of the 1293 * unbiased exponent as if produced by invoking {@link 1294 * Integer#toString(int) Integer.toString} on the exponent value. 1295 * 1296 * <li> If <i>m</i> is a {@code double} value with a subnormal 1297 * representation then the significand is represented by the characters 1298 * {@code '0x0.'} followed by the hexadecimal representation of the rest 1299 * of the significand as a fraction. The exponent is represented by 1300 * {@code 'p-1022'}. Note that there must be at least one nonzero digit 1301 * in a subnormal significand. 1302 * 1303 * </ul> 1304 * 1305 * <p> If the {@code '('} or {@code ','} flags are given, then a {@link 1306 * FormatFlagsConversionMismatchException} will be thrown. 1307 * 1308 * <tr><td valign="top"> {@code 'A'} 1309 * <td valign="top"> <tt>'\u0041'</tt> 1310 * <td> The upper-case variant of {@code 'a'}. The entire string 1311 * representing the number will be converted to upper case including the 1312 * {@code 'x'} (<tt>'\u0078'</tt>) and {@code 'p'} 1313 * (<tt>'\u0070'</tt> and all hexadecimal digits {@code 'a'} - 1314 * {@code 'f'} (<tt>'\u0061'</tt> - <tt>'\u0066'</tt>). 1315 * 1316 * </table> 1317 * 1318 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and 1319 * Long apply. 1320 * 1321 * <p> If the {@code '#'} flag is given, then the decimal separator will 1322 * always be present. 1323 * 1324 * <p> If no <a name="floatdFlags">flags</a> are given the default formatting 1325 * is as follows: 1326 * 1327 * <ul> 1328 * 1329 * <li> The output is right-justified within the {@code width} 1330 * 1331 * <li> Negative numbers begin with a {@code '-'} 1332 * 1333 * <li> Positive numbers and positive zero do not include a sign or extra 1334 * leading space 1335 * 1336 * <li> No grouping separators are included 1337 * 1338 * <li> The decimal separator will only appear if a digit follows it 1339 * 1340 * </ul> 1341 * 1342 * <p> The <a name="floatDWidth">width</a> is the minimum number of characters 1343 * to be written to the output. This includes any signs, digits, grouping 1344 * separators, decimal separators, exponential symbol, radix indicator, 1345 * parentheses, and strings representing infinity and NaN as applicable. If 1346 * the length of the converted value is less than the width then the output 1347 * will be padded by spaces (<tt>'\u0020'</tt>) until the total number of 1348 * characters equals width. The padding is on the left by default. If the 1349 * {@code '-'} flag is given then the padding will be on the right. If width 1350 * is not specified then there is no minimum. 1351 * 1352 * <p> If the <a name="floatDPrec">conversion</a> is {@code 'e'}, 1353 * {@code 'E'} or {@code 'f'}, then the precision is the number of digits 1354 * after the decimal separator. If the precision is not specified, then it is 1355 * assumed to be {@code 6}. 1356 * 1357 * <p> If the conversion is {@code 'g'} or {@code 'G'}, then the precision is 1358 * the total number of significant digits in the resulting magnitude after 1359 * rounding. If the precision is not specified, then the default value is 1360 * {@code 6}. If the precision is {@code 0}, then it is taken to be 1361 * {@code 1}. 1362 * 1363 * <p> If the conversion is {@code 'a'} or {@code 'A'}, then the precision 1364 * is the number of hexadecimal digits after the decimal separator. If the 1365 * precision is not provided, then all of the digits as returned by {@link 1366 * Double#toHexString(double)} will be output. 1367 * 1368 * <p><a name="dnbdec"><b> BigDecimal </b></a> 1369 * 1370 * <p> The following conversions may be applied {@link java.math.BigDecimal 1371 * BigDecimal}. 1372 * 1373 * <table cellpadding=5 summary="floatConv"> 1374 * 1375 * <tr><td valign="top"> {@code 'e'} 1376 * <td valign="top"> <tt>'\u0065'</tt> 1377 * <td> Requires the output to be formatted using <a 1378 * name="bscientific">computerized scientific notation</a>. The <a 1379 * href="#l10n algorithm">localization algorithm</a> is applied. 1380 * 1381 * <p> The formatting of the magnitude <i>m</i> depends upon its value. 1382 * 1383 * <p> If <i>m</i> is positive-zero or negative-zero, then the exponent 1384 * will be {@code "+00"}. 1385 * 1386 * <p> Otherwise, the result is a string that represents the sign and 1387 * magnitude (absolute value) of the argument. The formatting of the sign 1388 * is described in the <a href="#l10n algorithm">localization 1389 * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its 1390 * value. 1391 * 1392 * <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup> 1393 * <= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the 1394 * mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so 1395 * that 1 <= <i>a</i> < 10. The magnitude is then represented as the 1396 * integer part of <i>a</i>, as a single decimal digit, followed by the 1397 * decimal separator followed by decimal digits representing the fractional 1398 * part of <i>a</i>, followed by the exponent symbol {@code 'e'} 1399 * (<tt>'\u0065'</tt>), followed by the sign of the exponent, followed 1400 * by a representation of <i>n</i> as a decimal integer, as produced by the 1401 * method {@link Long#toString(long, int)}, and zero-padded to include at 1402 * least two digits. 1403 * 1404 * <p> The number of digits in the result for the fractional part of 1405 * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not 1406 * specified then the default value is {@code 6}. If the precision is 1407 * less than the number of digits to the right of the decimal point then 1408 * the value will be rounded using the 1409 * {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up 1410 * algorithm}. Otherwise, zeros may be appended to reach the precision. 1411 * For a canonical representation of the value, use {@link 1412 * BigDecimal#toString()}. 1413 * 1414 * <p> If the {@code ','} flag is given, then an {@link 1415 * FormatFlagsConversionMismatchException} will be thrown. 1416 * 1417 * <tr><td valign="top"> {@code 'E'} 1418 * <td valign="top"> <tt>'\u0045'</tt> 1419 * <td> The upper-case variant of {@code 'e'}. The exponent symbol 1420 * will be {@code 'E'} (<tt>'\u0045'</tt>). 1421 * 1422 * <tr><td valign="top"> {@code 'g'} 1423 * <td valign="top"> <tt>'\u0067'</tt> 1424 * <td> Requires the output to be formatted in general scientific notation 1425 * as described below. The <a href="#l10n algorithm">localization 1426 * algorithm</a> is applied. 1427 * 1428 * <p> After rounding for the precision, the formatting of the resulting 1429 * magnitude <i>m</i> depends on its value. 1430 * 1431 * <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less 1432 * than 10<sup>precision</sup> then it is represented in <i><a 1433 * href="#bdecimal">decimal format</a></i>. 1434 * 1435 * <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to 1436 * 10<sup>precision</sup>, then it is represented in <i><a 1437 * href="#bscientific">computerized scientific notation</a></i>. 1438 * 1439 * <p> The total number of significant digits in <i>m</i> is equal to the 1440 * precision. If the precision is not specified, then the default value is 1441 * {@code 6}. If the precision is {@code 0}, then it is taken to be 1442 * {@code 1}. 1443 * 1444 * <p> If the {@code '#'} flag is given then an {@link 1445 * FormatFlagsConversionMismatchException} will be thrown. 1446 * 1447 * <tr><td valign="top"> {@code 'G'} 1448 * <td valign="top"> <tt>'\u0047'</tt> 1449 * <td> The upper-case variant of {@code 'g'}. 1450 * 1451 * <tr><td valign="top"> {@code 'f'} 1452 * <td valign="top"> <tt>'\u0066'</tt> 1453 * <td> Requires the output to be formatted using <a name="bdecimal">decimal 1454 * format</a>. The <a href="#l10n algorithm">localization algorithm</a> is 1455 * applied. 1456 * 1457 * <p> The result is a string that represents the sign and magnitude 1458 * (absolute value) of the argument. The formatting of the sign is 1459 * described in the <a href="#l10n algorithm">localization 1460 * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its 1461 * value. 1462 * 1463 * <p> The magnitude is formatted as the integer part of <i>m</i>, with no 1464 * leading zeroes, followed by the decimal separator followed by one or 1465 * more decimal digits representing the fractional part of <i>m</i>. 1466 * 1467 * <p> The number of digits in the result for the fractional part of 1468 * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not 1469 * specified then the default value is {@code 6}. If the precision is 1470 * less than the number of digits to the right of the decimal point 1471 * then the value will be rounded using the 1472 * {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up 1473 * algorithm}. Otherwise, zeros may be appended to reach the precision. 1474 * For a canonical representation of the value, use {@link 1475 * BigDecimal#toString()}. 1476 * 1477 * </table> 1478 * 1479 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and 1480 * Long apply. 1481 * 1482 * <p> If the {@code '#'} flag is given, then the decimal separator will 1483 * always be present. 1484 * 1485 * <p> The <a href="#floatdFlags">default behavior</a> when no flags are 1486 * given is the same as for Float and Double. 1487 * 1488 * <p> The specification of <a href="#floatDWidth">width</a> and <a 1489 * href="#floatDPrec">precision</a> is the same as defined for Float and 1490 * Double. 1491 * 1492 * <h4><a name="ddt">Date/Time</a></h4> 1493 * 1494 * <p> This conversion may be applied to {@code long}, {@link Long}, {@link 1495 * Calendar}, and {@link Date}. 1496 * 1497 * <table cellpadding=5 summary="DTConv"> 1498 * 1499 * <tr><td valign="top"> {@code 't'} 1500 * <td valign="top"> <tt>'\u0074'</tt> 1501 * <td> Prefix for date and time conversion characters. 1502 * <tr><td valign="top"> {@code 'T'} 1503 * <td valign="top"> <tt>'\u0054'</tt> 1504 * <td> The upper-case variant of {@code 't'}. 1505 * 1506 * </table> 1507 * 1508 * <p> The following date and time conversion character suffixes are defined 1509 * for the {@code 't'} and {@code 'T'} conversions. The types are similar to 1510 * but not completely identical to those defined by GNU {@code date} and 1511 * POSIX {@code strftime(3c)}. Additional conversion types are provided to 1512 * access Java-specific functionality (e.g. {@code 'L'} for milliseconds 1513 * within the second). 1514 * 1515 * <p> The following conversion characters are used for formatting times: 1516 * 1517 * <table cellpadding=5 summary="time"> 1518 * 1519 * <tr><td valign="top"> {@code 'H'} 1520 * <td valign="top"> <tt>'\u0048'</tt> 1521 * <td> Hour of the day for the 24-hour clock, formatted as two digits with 1522 * a leading zero as necessary i.e. {@code 00 - 23}. {@code 00} 1523 * corresponds to midnight. 1524 * 1525 * <tr><td valign="top">{@code 'I'} 1526 * <td valign="top"> <tt>'\u0049'</tt> 1527 * <td> Hour for the 12-hour clock, formatted as two digits with a leading 1528 * zero as necessary, i.e. {@code 01 - 12}. {@code 01} corresponds to 1529 * one o'clock (either morning or afternoon). 1530 * 1531 * <tr><td valign="top">{@code 'k'} 1532 * <td valign="top"> <tt>'\u006b'</tt> 1533 * <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}. 1534 * {@code 0} corresponds to midnight. 1535 * 1536 * <tr><td valign="top">{@code 'l'} 1537 * <td valign="top"> <tt>'\u006c'</tt> 1538 * <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}. {@code 1} 1539 * corresponds to one o'clock (either morning or afternoon). 1540 * 1541 * <tr><td valign="top">{@code 'M'} 1542 * <td valign="top"> <tt>'\u004d'</tt> 1543 * <td> Minute within the hour formatted as two digits with a leading zero 1544 * as necessary, i.e. {@code 00 - 59}. 1545 * 1546 * <tr><td valign="top">{@code 'S'} 1547 * <td valign="top"> <tt>'\u0053'</tt> 1548 * <td> Seconds within the minute, formatted as two digits with a leading 1549 * zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special 1550 * value required to support leap seconds). 1551 * 1552 * <tr><td valign="top">{@code 'L'} 1553 * <td valign="top"> <tt>'\u004c'</tt> 1554 * <td> Millisecond within the second formatted as three digits with 1555 * leading zeros as necessary, i.e. {@code 000 - 999}. 1556 * 1557 * <tr><td valign="top">{@code 'N'} 1558 * <td valign="top"> <tt>'\u004e'</tt> 1559 * <td> Nanosecond within the second, formatted as nine digits with leading 1560 * zeros as necessary, i.e. {@code 000000000 - 999999999}. The precision 1561 * of this value is limited by the resolution of the underlying operating 1562 * system or hardware. 1563 * 1564 * <tr><td valign="top">{@code 'p'} 1565 * <td valign="top"> <tt>'\u0070'</tt> 1566 * <td> Locale-specific {@linkplain 1567 * java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker 1568 * in lower case, e.g."{@code am}" or "{@code pm}". Use of the 1569 * conversion prefix {@code 'T'} forces this output to upper case. (Note 1570 * that {@code 'p'} produces lower-case output. This is different from 1571 * GNU {@code date} and POSIX {@code strftime(3c)} which produce 1572 * upper-case output.) 1573 * 1574 * <tr><td valign="top">{@code 'z'} 1575 * <td valign="top"> <tt>'\u007a'</tt> 1576 * <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a> 1577 * style numeric time zone offset from GMT, e.g. {@code -0800}. This 1578 * value will be adjusted as necessary for Daylight Saving Time. For 1579 * {@code long}, {@link Long}, and {@link Date} the time zone used is 1580 * the {@linkplain TimeZone#getDefault() default time zone} for this 1581 * instance of the Java virtual machine. 1582 * 1583 * <tr><td valign="top">{@code 'Z'} 1584 * <td valign="top"> <tt>'\u005a'</tt> 1585 * <td> A string representing the abbreviation for the time zone. This 1586 * value will be adjusted as necessary for Daylight Saving Time. For 1587 * {@code long}, {@link Long}, and {@link Date} the time zone used is 1588 * the {@linkplain TimeZone#getDefault() default time zone} for this 1589 * instance of the Java virtual machine. The Formatter's locale will 1590 * supersede the locale of the argument (if any). 1591 * 1592 * <tr><td valign="top">{@code 's'} 1593 * <td valign="top"> <tt>'\u0073'</tt> 1594 * <td> Seconds since the beginning of the epoch starting at 1 January 1970 1595 * {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to 1596 * {@code Long.MAX_VALUE/1000}. 1597 * 1598 * <tr><td valign="top">{@code 'Q'} 1599 * <td valign="top"> <tt>'\u004f'</tt> 1600 * <td> Milliseconds since the beginning of the epoch starting at 1 January 1601 * 1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to 1602 * {@code Long.MAX_VALUE}. The precision of this value is limited by 1603 * the resolution of the underlying operating system or hardware. 1604 * 1605 * </table> 1606 * 1607 * <p> The following conversion characters are used for formatting dates: 1608 * 1609 * <table cellpadding=5 summary="date"> 1610 * 1611 * <tr><td valign="top">{@code 'B'} 1612 * <td valign="top"> <tt>'\u0042'</tt> 1613 * <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths 1614 * full month name}, e.g. {@code "January"}, {@code "February"}. 1615 * 1616 * <tr><td valign="top">{@code 'b'} 1617 * <td valign="top"> <tt>'\u0062'</tt> 1618 * <td> Locale-specific {@linkplain 1619 * java.text.DateFormatSymbols#getShortMonths abbreviated month name}, 1620 * e.g. {@code "Jan"}, {@code "Feb"}. 1621 * 1622 * <tr><td valign="top">{@code 'h'} 1623 * <td valign="top"> <tt>'\u0068'</tt> 1624 * <td> Same as {@code 'b'}. 1625 * 1626 * <tr><td valign="top">{@code 'A'} 1627 * <td valign="top"> <tt>'\u0041'</tt> 1628 * <td> Locale-specific full name of the {@linkplain 1629 * java.text.DateFormatSymbols#getWeekdays day of the week}, 1630 * e.g. {@code "Sunday"}, {@code "Monday"} 1631 * 1632 * <tr><td valign="top">{@code 'a'} 1633 * <td valign="top"> <tt>'\u0061'</tt> 1634 * <td> Locale-specific short name of the {@linkplain 1635 * java.text.DateFormatSymbols#getShortWeekdays day of the week}, 1636 * e.g. {@code "Sun"}, {@code "Mon"} 1637 * 1638 * <tr><td valign="top">{@code 'C'} 1639 * <td valign="top"> <tt>'\u0043'</tt> 1640 * <td> Four-digit year divided by {@code 100}, formatted as two digits 1641 * with leading zero as necessary, i.e. {@code 00 - 99} 1642 * 1643 * <tr><td valign="top">{@code 'Y'} 1644 * <td valign="top"> <tt>'\u0059'</tt> <td> Year, formatted to at least 1645 * four digits with leading zeros as necessary, e.g. {@code 0092} equals 1646 * {@code 92} CE for the Gregorian calendar. 1647 * 1648 * <tr><td valign="top">{@code 'y'} 1649 * <td valign="top"> <tt>'\u0079'</tt> 1650 * <td> Last two digits of the year, formatted with leading zeros as 1651 * necessary, i.e. {@code 00 - 99}. 1652 * 1653 * <tr><td valign="top">{@code 'j'} 1654 * <td valign="top"> <tt>'\u006a'</tt> 1655 * <td> Day of year, formatted as three digits with leading zeros as 1656 * necessary, e.g. {@code 001 - 366} for the Gregorian calendar. 1657 * {@code 001} corresponds to the first day of the year. 1658 * 1659 * <tr><td valign="top">{@code 'm'} 1660 * <td valign="top"> <tt>'\u006d'</tt> 1661 * <td> Month, formatted as two digits with leading zeros as necessary, 1662 * i.e. {@code 01 - 13}, where "{@code 01}" is the first month of the 1663 * year and ("{@code 13}" is a special value required to support lunar 1664 * calendars). 1665 * 1666 * <tr><td valign="top">{@code 'd'} 1667 * <td valign="top"> <tt>'\u0064'</tt> 1668 * <td> Day of month, formatted as two digits with leading zeros as 1669 * necessary, i.e. {@code 01 - 31}, where "{@code 01}" is the first day 1670 * of the month. 1671 * 1672 * <tr><td valign="top">{@code 'e'} 1673 * <td valign="top"> <tt>'\u0065'</tt> 1674 * <td> Day of month, formatted as two digits, i.e. {@code 1 - 31} where 1675 * "{@code 1}" is the first day of the month. 1676 * 1677 * </table> 1678 * 1679 * <p> The following conversion characters are used for formatting common 1680 * date/time compositions. 1681 * 1682 * <table cellpadding=5 summary="composites"> 1683 * 1684 * <tr><td valign="top">{@code 'R'} 1685 * <td valign="top"> <tt>'\u0052'</tt> 1686 * <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"} 1687 * 1688 * <tr><td valign="top">{@code 'T'} 1689 * <td valign="top"> <tt>'\u0054'</tt> 1690 * <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}. 1691 * 1692 * <tr><td valign="top">{@code 'r'} 1693 * <td valign="top"> <tt>'\u0072'</tt> 1694 * <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS 1695 * %Tp"}. The location of the morning or afternoon marker 1696 * ({@code '%Tp'}) may be locale-dependent. 1697 * 1698 * <tr><td valign="top">{@code 'D'} 1699 * <td valign="top"> <tt>'\u0044'</tt> 1700 * <td> Date formatted as {@code "%tm/%td/%ty"}. 1701 * 1702 * <tr><td valign="top">{@code 'F'} 1703 * <td valign="top"> <tt>'\u0046'</tt> 1704 * <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> 1705 * complete date formatted as {@code "%tY-%tm-%td"}. 1706 * 1707 * <tr><td valign="top">{@code 'c'} 1708 * <td valign="top"> <tt>'\u0063'</tt> 1709 * <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"}, 1710 * e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}. 1711 * 1712 * </table> 1713 * 1714 * <p> The {@code '-'} flag defined for <a href="#dFlags">General 1715 * conversions</a> applies. If the {@code '#'} flag is given, then a {@link 1716 * FormatFlagsConversionMismatchException} will be thrown. 1717 * 1718 * <p> The <a name="dtWidth">width</a> is the minimum number of characters to 1719 * be written to the output. If the length of the converted value is less than 1720 * the {@code width} then the output will be padded by spaces 1721 * (<tt>'\u0020'</tt>) until the total number of characters equals width. 1722 * The padding is on the left by default. If the {@code '-'} flag is given 1723 * then the padding will be on the right. If width is not specified then there 1724 * is no minimum. 1725 * 1726 * <p> The precision is not applicable. If the precision is specified then an 1727 * {@link IllegalFormatPrecisionException} will be thrown. 1728 * 1729 * <h4><a name="dper">Percent</a></h4> 1730 * 1731 * <p> The conversion does not correspond to any argument. 1732 * 1733 * <table cellpadding=5 summary="DTConv"> 1734 * 1735 * <tr><td valign="top">{@code '%'} 1736 * <td> The result is a literal {@code '%'} (<tt>'\u0025'</tt>) 1737 * 1738 * <p> The <a name="dtWidth">width</a> is the minimum number of characters to 1739 * be written to the output including the {@code '%'}. If the length of the 1740 * converted value is less than the {@code width} then the output will be 1741 * padded by spaces (<tt>'\u0020'</tt>) until the total number of 1742 * characters equals width. The padding is on the left. If width is not 1743 * specified then just the {@code '%'} is output. 1744 * 1745 * <p> The {@code '-'} flag defined for <a href="#dFlags">General 1746 * conversions</a> applies. If any other flags are provided, then a 1747 * {@link FormatFlagsConversionMismatchException} will be thrown. 1748 * 1749 * <p> The precision is not applicable. If the precision is specified an 1750 * {@link IllegalFormatPrecisionException} will be thrown. 1751 * 1752 * </table> 1753 * 1754 * <h4><a name="dls">Line Separator</a></h4> 1755 * 1756 * <p> The conversion does not correspond to any argument. 1757 * 1758 * <table cellpadding=5 summary="DTConv"> 1759 * 1760 * <tr><td valign="top">{@code 'n'} 1761 * <td> the platform-specific line separator as returned by {@link 1762 * System#getProperty System.getProperty("line.separator")}. 1763 * 1764 * </table> 1765 * 1766 * <p> Flags, width, and precision are not applicable. If any are provided an 1767 * {@link IllegalFormatFlagsException}, {@link IllegalFormatWidthException}, 1768 * and {@link IllegalFormatPrecisionException}, respectively will be thrown. 1769 * 1770 * <h4><a name="dpos">Argument Index</a></h4> 1771 * 1772 * <p> Format specifiers can reference arguments in three ways: 1773 * 1774 * <ul> 1775 * 1776 * <li> <i>Explicit indexing</i> is used when the format specifier contains an 1777 * argument index. The argument index is a decimal integer indicating the 1778 * position of the argument in the argument list. The first argument is 1779 * referenced by "{@code 1$}", the second by "{@code 2$}", etc. An argument 1780 * may be referenced more than once. 1781 * 1782 * <p> For example: 1783 * 1784 * <blockquote><pre> 1785 * formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s", 1786 * "a", "b", "c", "d") 1787 * // -> "d c b a d c b a" 1788 * </pre></blockquote> 1789 * 1790 * <li> <i>Relative indexing</i> is used when the format specifier contains a 1791 * {@code '<'} (<tt>'\u003c'</tt>) flag which causes the argument for 1792 * the previous format specifier to be re-used. If there is no previous 1793 * argument, then a {@link MissingFormatArgumentException} is thrown. 1794 * 1795 * <blockquote><pre> 1796 * formatter.format("%s %s %<s %<s", "a", "b", "c", "d") 1797 * // -> "a b b b" 1798 * // "c" and "d" are ignored because they are not referenced 1799 * </pre></blockquote> 1800 * 1801 * <li> <i>Ordinary indexing</i> is used when the format specifier contains 1802 * neither an argument index nor a {@code '<'} flag. Each format specifier 1803 * which uses ordinary indexing is assigned a sequential implicit index into 1804 * argument list which is independent of the indices used by explicit or 1805 * relative indexing. 1806 * 1807 * <blockquote><pre> 1808 * formatter.format("%s %s %s %s", "a", "b", "c", "d") 1809 * // -> "a b c d" 1810 * </pre></blockquote> 1811 * 1812 * </ul> 1813 * 1814 * <p> It is possible to have a format string which uses all forms of indexing, 1815 * for example: 1816 * 1817 * <blockquote><pre> 1818 * formatter.format("%2$s %s %<s %s", "a", "b", "c", "d") 1819 * // -> "b a a b" 1820 * // "c" and "d" are ignored because they are not referenced 1821 * </pre></blockquote> 1822 * 1823 * <p> The maximum number of arguments is limited by the maximum dimension of a 1824 * Java array as defined by 1825 * <cite>The Java™ Virtual Machine Specification</cite>. 1826 * If the argument index is does not correspond to an 1827 * available argument, then a {@link MissingFormatArgumentException} is thrown. 1828 * 1829 * <p> If there are more arguments than format specifiers, the extra arguments 1830 * are ignored. 1831 * 1832 * <p> Unless otherwise specified, passing a {@code null} argument to any 1833 * method or constructor in this class will cause a {@link 1834 * NullPointerException} to be thrown. 1835 * 1836 * @author Iris Clark 1837 * @since 1.5 1838 */ 1839public final class Formatter implements Closeable, Flushable { 1840 private Appendable a; 1841 private final Locale l; 1842 1843 private IOException lastException; 1844 1845 private final char zero; 1846 private static double scaleUp; 1847 1848 // 1 (sign) + 19 (max # sig digits) + 1 ('.') + 1 ('e') + 1 (sign) 1849 // + 3 (max # exp digits) + 4 (error) = 30 1850 private static final int MAX_FD_CHARS = 30; 1851 1852 /** 1853 * Returns a charset object for the given charset name. 1854 * @throws NullPointerException is csn is null 1855 * @throws UnsupportedEncodingException if the charset is not supported 1856 */ 1857 private static Charset toCharset(String csn) 1858 throws UnsupportedEncodingException 1859 { 1860 Objects.requireNonNull(csn, "charsetName"); 1861 try { 1862 return Charset.forName(csn); 1863 } catch (IllegalCharsetNameException|UnsupportedCharsetException unused) { 1864 // UnsupportedEncodingException should be thrown 1865 throw new UnsupportedEncodingException(csn); 1866 } 1867 } 1868 1869 private static final Appendable nonNullAppendable(Appendable a) { 1870 if (a == null) 1871 return new StringBuilder(); 1872 1873 return a; 1874 } 1875 1876 /* Private constructors */ 1877 private Formatter(Locale l, Appendable a) { 1878 this.a = a; 1879 this.l = l; 1880 this.zero = getZero(l); 1881 } 1882 1883 private Formatter(Charset charset, Locale l, File file) 1884 throws FileNotFoundException 1885 { 1886 this(l, 1887 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset))); 1888 } 1889 1890 /** 1891 * Constructs a new formatter. 1892 * 1893 * <p> The destination of the formatted output is a {@link StringBuilder} 1894 * which may be retrieved by invoking {@link #out out()} and whose 1895 * current content may be converted into a string by invoking {@link 1896 * #toString toString()}. The locale used is the {@linkplain 1897 * Locale#getDefault() default locale} for this instance of the Java 1898 * virtual machine. 1899 */ 1900 public Formatter() { 1901 this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder()); 1902 } 1903 1904 /** 1905 * Constructs a new formatter with the specified destination. 1906 * 1907 * <p> The locale used is the {@linkplain Locale#getDefault() default 1908 * locale} for this instance of the Java virtual machine. 1909 * 1910 * @param a 1911 * Destination for the formatted output. If {@code a} is 1912 * {@code null} then a {@link StringBuilder} will be created. 1913 */ 1914 public Formatter(Appendable a) { 1915 this(Locale.getDefault(Locale.Category.FORMAT), nonNullAppendable(a)); 1916 } 1917 1918 /** 1919 * Constructs a new formatter with the specified locale. 1920 * 1921 * <p> The destination of the formatted output is a {@link StringBuilder} 1922 * which may be retrieved by invoking {@link #out out()} and whose current 1923 * content may be converted into a string by invoking {@link #toString 1924 * toString()}. 1925 * 1926 * @param l 1927 * The {@linkplain java.util.Locale locale} to apply during 1928 * formatting. If {@code l} is {@code null} then no localization 1929 * is applied. 1930 */ 1931 public Formatter(Locale l) { 1932 this(l, new StringBuilder()); 1933 } 1934 1935 /** 1936 * Constructs a new formatter with the specified destination and locale. 1937 * 1938 * @param a 1939 * Destination for the formatted output. If {@code a} is 1940 * {@code null} then a {@link StringBuilder} will be created. 1941 * 1942 * @param l 1943 * The {@linkplain java.util.Locale locale} to apply during 1944 * formatting. If {@code l} is {@code null} then no localization 1945 * is applied. 1946 */ 1947 public Formatter(Appendable a, Locale l) { 1948 this(l, nonNullAppendable(a)); 1949 } 1950 1951 /** 1952 * Constructs a new formatter with the specified file name. 1953 * 1954 * <p> The charset used is the {@linkplain 1955 * java.nio.charset.Charset#defaultCharset() default charset} for this 1956 * instance of the Java virtual machine. 1957 * 1958 * <p> The locale used is the {@linkplain Locale#getDefault() default 1959 * locale} for this instance of the Java virtual machine. 1960 * 1961 * @param fileName 1962 * The name of the file to use as the destination of this 1963 * formatter. If the file exists then it will be truncated to 1964 * zero size; otherwise, a new file will be created. The output 1965 * will be written to the file and is buffered. 1966 * 1967 * @throws SecurityException 1968 * If a security manager is present and {@link 1969 * SecurityManager#checkWrite checkWrite(fileName)} denies write 1970 * access to the file 1971 * 1972 * @throws FileNotFoundException 1973 * If the given file name does not denote an existing, writable 1974 * regular file and a new regular file of that name cannot be 1975 * created, or if some other error occurs while opening or 1976 * creating the file 1977 */ 1978 public Formatter(String fileName) throws FileNotFoundException { 1979 this(Locale.getDefault(Locale.Category.FORMAT), 1980 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)))); 1981 } 1982 1983 /** 1984 * Constructs a new formatter with the specified file name and charset. 1985 * 1986 * <p> The locale used is the {@linkplain Locale#getDefault default 1987 * locale} for this instance of the Java virtual machine. 1988 * 1989 * @param fileName 1990 * The name of the file to use as the destination of this 1991 * formatter. If the file exists then it will be truncated to 1992 * zero size; otherwise, a new file will be created. The output 1993 * will be written to the file and is buffered. 1994 * 1995 * @param csn 1996 * The name of a supported {@linkplain java.nio.charset.Charset 1997 * charset} 1998 * 1999 * @throws FileNotFoundException 2000 * If the given file name does not denote an existing, writable 2001 * regular file and a new regular file of that name cannot be 2002 * created, or if some other error occurs while opening or 2003 * creating the file 2004 * 2005 * @throws SecurityException 2006 * If a security manager is present and {@link 2007 * SecurityManager#checkWrite checkWrite(fileName)} denies write 2008 * access to the file 2009 * 2010 * @throws UnsupportedEncodingException 2011 * If the named charset is not supported 2012 */ 2013 public Formatter(String fileName, String csn) 2014 throws FileNotFoundException, UnsupportedEncodingException 2015 { 2016 this(fileName, csn, Locale.getDefault(Locale.Category.FORMAT)); 2017 } 2018 2019 /** 2020 * Constructs a new formatter with the specified file name, charset, and 2021 * locale. 2022 * 2023 * @param fileName 2024 * The name of the file to use as the destination of this 2025 * formatter. If the file exists then it will be truncated to 2026 * zero size; otherwise, a new file will be created. The output 2027 * will be written to the file and is buffered. 2028 * 2029 * @param csn 2030 * The name of a supported {@linkplain java.nio.charset.Charset 2031 * charset} 2032 * 2033 * @param l 2034 * The {@linkplain java.util.Locale locale} to apply during 2035 * formatting. If {@code l} is {@code null} then no localization 2036 * is applied. 2037 * 2038 * @throws FileNotFoundException 2039 * If the given file name does not denote an existing, writable 2040 * regular file and a new regular file of that name cannot be 2041 * created, or if some other error occurs while opening or 2042 * creating the file 2043 * 2044 * @throws SecurityException 2045 * If a security manager is present and {@link 2046 * SecurityManager#checkWrite checkWrite(fileName)} denies write 2047 * access to the file 2048 * 2049 * @throws UnsupportedEncodingException 2050 * If the named charset is not supported 2051 */ 2052 public Formatter(String fileName, String csn, Locale l) 2053 throws FileNotFoundException, UnsupportedEncodingException 2054 { 2055 this(toCharset(csn), l, new File(fileName)); 2056 } 2057 2058 /** 2059 * Constructs a new formatter with the specified file. 2060 * 2061 * <p> The charset used is the {@linkplain 2062 * java.nio.charset.Charset#defaultCharset() default charset} for this 2063 * instance of the Java virtual machine. 2064 * 2065 * <p> The locale used is the {@linkplain Locale#getDefault() default 2066 * locale} for this instance of the Java virtual machine. 2067 * 2068 * @param file 2069 * The file to use as the destination of this formatter. If the 2070 * file exists then it will be truncated to zero size; otherwise, 2071 * a new file will be created. The output will be written to the 2072 * file and is buffered. 2073 * 2074 * @throws SecurityException 2075 * If a security manager is present and {@link 2076 * SecurityManager#checkWrite checkWrite(file.getPath())} denies 2077 * write access to the file 2078 * 2079 * @throws FileNotFoundException 2080 * If the given file object does not denote an existing, writable 2081 * regular file and a new regular file of that name cannot be 2082 * created, or if some other error occurs while opening or 2083 * creating the file 2084 */ 2085 public Formatter(File file) throws FileNotFoundException { 2086 this(Locale.getDefault(Locale.Category.FORMAT), 2087 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))); 2088 } 2089 2090 /** 2091 * Constructs a new formatter with the specified file and charset. 2092 * 2093 * <p> The locale used is the {@linkplain Locale#getDefault default 2094 * locale} for this instance of the Java virtual machine. 2095 * 2096 * @param file 2097 * The file to use as the destination of this formatter. If the 2098 * file exists then it will be truncated to zero size; otherwise, 2099 * a new file will be created. The output will be written to the 2100 * file and is buffered. 2101 * 2102 * @param csn 2103 * The name of a supported {@linkplain java.nio.charset.Charset 2104 * charset} 2105 * 2106 * @throws FileNotFoundException 2107 * If the given file object does not denote an existing, writable 2108 * regular file and a new regular file of that name cannot be 2109 * created, or if some other error occurs while opening or 2110 * creating the file 2111 * 2112 * @throws SecurityException 2113 * If a security manager is present and {@link 2114 * SecurityManager#checkWrite checkWrite(file.getPath())} denies 2115 * write access to the file 2116 * 2117 * @throws UnsupportedEncodingException 2118 * If the named charset is not supported 2119 */ 2120 public Formatter(File file, String csn) 2121 throws FileNotFoundException, UnsupportedEncodingException 2122 { 2123 this(file, csn, Locale.getDefault(Locale.Category.FORMAT)); 2124 } 2125 2126 /** 2127 * Constructs a new formatter with the specified file, charset, and 2128 * locale. 2129 * 2130 * @param file 2131 * The file to use as the destination of this formatter. If the 2132 * file exists then it will be truncated to zero size; otherwise, 2133 * a new file will be created. The output will be written to the 2134 * file and is buffered. 2135 * 2136 * @param csn 2137 * The name of a supported {@linkplain java.nio.charset.Charset 2138 * charset} 2139 * 2140 * @param l 2141 * The {@linkplain java.util.Locale locale} to apply during 2142 * formatting. If {@code l} is {@code null} then no localization 2143 * is applied. 2144 * 2145 * @throws FileNotFoundException 2146 * If the given file object does not denote an existing, writable 2147 * regular file and a new regular file of that name cannot be 2148 * created, or if some other error occurs while opening or 2149 * creating the file 2150 * 2151 * @throws SecurityException 2152 * If a security manager is present and {@link 2153 * SecurityManager#checkWrite checkWrite(file.getPath())} denies 2154 * write access to the file 2155 * 2156 * @throws UnsupportedEncodingException 2157 * If the named charset is not supported 2158 */ 2159 public Formatter(File file, String csn, Locale l) 2160 throws FileNotFoundException, UnsupportedEncodingException 2161 { 2162 this(toCharset(csn), l, file); 2163 } 2164 2165 /** 2166 * Constructs a new formatter with the specified print stream. 2167 * 2168 * <p> The locale used is the {@linkplain Locale#getDefault() default 2169 * locale} for this instance of the Java virtual machine. 2170 * 2171 * <p> Characters are written to the given {@link java.io.PrintStream 2172 * PrintStream} object and are therefore encoded using that object's 2173 * charset. 2174 * 2175 * @param ps 2176 * The stream to use as the destination of this formatter. 2177 */ 2178 public Formatter(PrintStream ps) { 2179 this(Locale.getDefault(Locale.Category.FORMAT), 2180 (Appendable)Objects.requireNonNull(ps)); 2181 } 2182 2183 /** 2184 * Constructs a new formatter with the specified output stream. 2185 * 2186 * <p> The charset used is the {@linkplain 2187 * java.nio.charset.Charset#defaultCharset() default charset} for this 2188 * instance of the Java virtual machine. 2189 * 2190 * <p> The locale used is the {@linkplain Locale#getDefault() default 2191 * locale} for this instance of the Java virtual machine. 2192 * 2193 * @param os 2194 * The output stream to use as the destination of this formatter. 2195 * The output will be buffered. 2196 */ 2197 public Formatter(OutputStream os) { 2198 this(Locale.getDefault(Locale.Category.FORMAT), 2199 new BufferedWriter(new OutputStreamWriter(os))); 2200 } 2201 2202 /** 2203 * Constructs a new formatter with the specified output stream and 2204 * charset. 2205 * 2206 * <p> The locale used is the {@linkplain Locale#getDefault default 2207 * locale} for this instance of the Java virtual machine. 2208 * 2209 * @param os 2210 * The output stream to use as the destination of this formatter. 2211 * The output will be buffered. 2212 * 2213 * @param csn 2214 * The name of a supported {@linkplain java.nio.charset.Charset 2215 * charset} 2216 * 2217 * @throws UnsupportedEncodingException 2218 * If the named charset is not supported 2219 */ 2220 public Formatter(OutputStream os, String csn) 2221 throws UnsupportedEncodingException 2222 { 2223 this(os, csn, Locale.getDefault(Locale.Category.FORMAT)); 2224 } 2225 2226 /** 2227 * Constructs a new formatter with the specified output stream, charset, 2228 * and locale. 2229 * 2230 * @param os 2231 * The output stream to use as the destination of this formatter. 2232 * The output will be buffered. 2233 * 2234 * @param csn 2235 * The name of a supported {@linkplain java.nio.charset.Charset 2236 * charset} 2237 * 2238 * @param l 2239 * The {@linkplain java.util.Locale locale} to apply during 2240 * formatting. If {@code l} is {@code null} then no localization 2241 * is applied. 2242 * 2243 * @throws UnsupportedEncodingException 2244 * If the named charset is not supported 2245 */ 2246 public Formatter(OutputStream os, String csn, Locale l) 2247 throws UnsupportedEncodingException 2248 { 2249 this(l, new BufferedWriter(new OutputStreamWriter(os, csn))); 2250 } 2251 2252 private static char getZero(Locale l) { 2253 if ((l != null) && !l.equals(Locale.US)) { 2254 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); 2255 return dfs.getZeroDigit(); 2256 } else { 2257 return '0'; 2258 } 2259 } 2260 2261 /** 2262 * Returns the locale set by the construction of this formatter. 2263 * 2264 * <p> The {@link #format(java.util.Locale,String,Object...) format} method 2265 * for this object which has a locale argument does not change this value. 2266 * 2267 * @return {@code null} if no localization is applied, otherwise a 2268 * locale 2269 * 2270 * @throws FormatterClosedException 2271 * If this formatter has been closed by invoking its {@link 2272 * #close()} method 2273 */ 2274 public Locale locale() { 2275 ensureOpen(); 2276 return l; 2277 } 2278 2279 /** 2280 * Returns the destination for the output. 2281 * 2282 * @return The destination for the output 2283 * 2284 * @throws FormatterClosedException 2285 * If this formatter has been closed by invoking its {@link 2286 * #close()} method 2287 */ 2288 public Appendable out() { 2289 ensureOpen(); 2290 return a; 2291 } 2292 2293 /** 2294 * Returns the result of invoking {@code toString()} on the destination 2295 * for the output. For example, the following code formats text into a 2296 * {@link StringBuilder} then retrieves the resultant string: 2297 * 2298 * <blockquote><pre> 2299 * Formatter f = new Formatter(); 2300 * f.format("Last reboot at %tc", lastRebootDate); 2301 * String s = f.toString(); 2302 * // -> s == "Last reboot at Sat Jan 01 00:00:00 PST 2000" 2303 * </pre></blockquote> 2304 * 2305 * <p> An invocation of this method behaves in exactly the same way as the 2306 * invocation 2307 * 2308 * <pre> 2309 * out().toString() </pre> 2310 * 2311 * <p> Depending on the specification of {@code toString} for the {@link 2312 * Appendable}, the returned string may or may not contain the characters 2313 * written to the destination. For instance, buffers typically return 2314 * their contents in {@code toString()}, but streams cannot since the 2315 * data is discarded. 2316 * 2317 * @return The result of invoking {@code toString()} on the destination 2318 * for the output 2319 * 2320 * @throws FormatterClosedException 2321 * If this formatter has been closed by invoking its {@link 2322 * #close()} method 2323 */ 2324 public String toString() { 2325 ensureOpen(); 2326 return a.toString(); 2327 } 2328 2329 /** 2330 * Flushes this formatter. If the destination implements the {@link 2331 * java.io.Flushable} interface, its {@code flush} method will be invoked. 2332 * 2333 * <p> Flushing a formatter writes any buffered output in the destination 2334 * to the underlying stream. 2335 * 2336 * @throws FormatterClosedException 2337 * If this formatter has been closed by invoking its {@link 2338 * #close()} method 2339 */ 2340 public void flush() { 2341 ensureOpen(); 2342 if (a instanceof Flushable) { 2343 try { 2344 ((Flushable)a).flush(); 2345 } catch (IOException ioe) { 2346 lastException = ioe; 2347 } 2348 } 2349 } 2350 2351 /** 2352 * Closes this formatter. If the destination implements the {@link 2353 * java.io.Closeable} interface, its {@code close} method will be invoked. 2354 * 2355 * <p> Closing a formatter allows it to release resources it may be holding 2356 * (such as open files). If the formatter is already closed, then invoking 2357 * this method has no effect. 2358 * 2359 * <p> Attempting to invoke any methods except {@link #ioException()} in 2360 * this formatter after it has been closed will result in a {@link 2361 * FormatterClosedException}. 2362 */ 2363 public void close() { 2364 if (a == null) 2365 return; 2366 try { 2367 if (a instanceof Closeable) 2368 ((Closeable)a).close(); 2369 } catch (IOException ioe) { 2370 lastException = ioe; 2371 } finally { 2372 a = null; 2373 } 2374 } 2375 2376 private void ensureOpen() { 2377 if (a == null) 2378 throw new FormatterClosedException(); 2379 } 2380 2381 /** 2382 * Returns the {@code IOException} last thrown by this formatter's {@link 2383 * Appendable}. 2384 * 2385 * <p> If the destination's {@code append()} method never throws 2386 * {@code IOException}, then this method will always return {@code null}. 2387 * 2388 * @return The last exception thrown by the Appendable or {@code null} if 2389 * no such exception exists. 2390 */ 2391 public IOException ioException() { 2392 return lastException; 2393 } 2394 2395 /** 2396 * Writes a formatted string to this object's destination using the 2397 * specified format string and arguments. The locale used is the one 2398 * defined during the construction of this formatter. 2399 * 2400 * @param format 2401 * A format string as described in <a href="#syntax">Format string 2402 * syntax</a>. 2403 * 2404 * @param args 2405 * Arguments referenced by the format specifiers in the format 2406 * string. If there are more arguments than format specifiers, the 2407 * extra arguments are ignored. The maximum number of arguments is 2408 * limited by the maximum dimension of a Java array as defined by 2409 * <cite>The Java™ Virtual Machine Specification</cite>. 2410 * 2411 * @throws IllegalFormatException 2412 * If a format string contains an illegal syntax, a format 2413 * specifier that is incompatible with the given arguments, 2414 * insufficient arguments given the format string, or other 2415 * illegal conditions. For specification of all possible 2416 * formatting errors, see the <a href="#detail">Details</a> 2417 * section of the formatter class specification. 2418 * 2419 * @throws FormatterClosedException 2420 * If this formatter has been closed by invoking its {@link 2421 * #close()} method 2422 * 2423 * @return This formatter 2424 */ 2425 public Formatter format(String format, Object ... args) { 2426 return format(l, format, args); 2427 } 2428 2429 /** 2430 * Writes a formatted string to this object's destination using the 2431 * specified locale, format string, and arguments. 2432 * 2433 * @param l 2434 * The {@linkplain java.util.Locale locale} to apply during 2435 * formatting. If {@code l} is {@code null} then no localization 2436 * is applied. This does not change this object's locale that was 2437 * set during construction. 2438 * 2439 * @param format 2440 * A format string as described in <a href="#syntax">Format string 2441 * syntax</a> 2442 * 2443 * @param args 2444 * Arguments referenced by the format specifiers in the format 2445 * string. If there are more arguments than format specifiers, the 2446 * extra arguments are ignored. The maximum number of arguments is 2447 * limited by the maximum dimension of a Java array as defined by 2448 * <cite>The Java™ Virtual Machine Specification</cite>. 2449 * 2450 * @throws IllegalFormatException 2451 * If a format string contains an illegal syntax, a format 2452 * specifier that is incompatible with the given arguments, 2453 * insufficient arguments given the format string, or other 2454 * illegal conditions. For specification of all possible 2455 * formatting errors, see the <a href="#detail">Details</a> 2456 * section of the formatter class specification. 2457 * 2458 * @throws FormatterClosedException 2459 * If this formatter has been closed by invoking its {@link 2460 * #close()} method 2461 * 2462 * @return This formatter 2463 */ 2464 public Formatter format(Locale l, String format, Object ... args) { 2465 ensureOpen(); 2466 2467 // index of last argument referenced 2468 int last = -1; 2469 // last ordinary index 2470 int lasto = -1; 2471 2472 FormatString[] fsa = parse(format); 2473 for (int i = 0; i < fsa.length; i++) { 2474 FormatString fs = fsa[i]; 2475 int index = fs.index(); 2476 try { 2477 switch (index) { 2478 case -2: // fixed string, "%n", or "%%" 2479 fs.print(null, l); 2480 break; 2481 case -1: // relative index 2482 if (last < 0 || (args != null && last > args.length - 1)) 2483 throw new MissingFormatArgumentException(fs.toString()); 2484 fs.print((args == null ? null : args[last]), l); 2485 break; 2486 case 0: // ordinary index 2487 lasto++; 2488 last = lasto; 2489 if (args != null && lasto > args.length - 1) 2490 throw new MissingFormatArgumentException(fs.toString()); 2491 fs.print((args == null ? null : args[lasto]), l); 2492 break; 2493 default: // explicit index 2494 last = index - 1; 2495 if (args != null && last > args.length - 1) 2496 throw new MissingFormatArgumentException(fs.toString()); 2497 fs.print((args == null ? null : args[last]), l); 2498 break; 2499 } 2500 } catch (IOException x) { 2501 lastException = x; 2502 } 2503 } 2504 return this; 2505 } 2506 2507 /** 2508 * Finds format specifiers in the format string. 2509 */ 2510 private FormatString[] parse(String s) { 2511 ArrayList<FormatString> al = new ArrayList<>(); 2512 for (int i = 0, len = s.length(); i < len; ) { 2513 int nextPercent = s.indexOf('%', i); 2514 if (s.charAt(i) != '%') { 2515 // This is plain-text part, find the maximal plain-text 2516 // sequence and store it. 2517 int plainTextStart = i; 2518 int plainTextEnd = (nextPercent == -1) ? len: nextPercent; 2519 al.add(new FixedString(s.substring(plainTextStart, 2520 plainTextEnd))); 2521 i = plainTextEnd; 2522 } else { 2523 // We have a format specifier 2524 FormatSpecifierParser fsp = new FormatSpecifierParser(s, i + 1); 2525 al.add(fsp.getFormatSpecifier()); 2526 i = fsp.getEndIdx(); 2527 } 2528 } 2529 return al.toArray(new FormatString[al.size()]); 2530 } 2531 2532 /** 2533 * Parses the format specifier. 2534 * %[argument_index$][flags][width][.precision][t]conversion 2535 */ 2536 private class FormatSpecifierParser { 2537 private final String format; 2538 private int cursor; 2539 private FormatSpecifier fs; 2540 2541 private String index; 2542 private String flags; 2543 private String width; 2544 private String precision; 2545 private String tT; 2546 private String conv; 2547 2548 private static final String FLAGS = ",-(+# 0<"; 2549 2550 public FormatSpecifierParser(String format, int startIdx) { 2551 this.format = format; 2552 cursor = startIdx; 2553 // Index 2554 if (nextIsInt()) { 2555 String nint = nextInt(); 2556 if (peek() == '$') { 2557 index = nint; 2558 advance(); 2559 } else if (nint.charAt(0) == '0') { 2560 // This is a flag, skip to parsing flags. 2561 back(nint.length()); 2562 } else { 2563 // This is the width, skip to parsing precision. 2564 width = nint; 2565 } 2566 } 2567 // Flags 2568 flags = ""; 2569 while (width == null && FLAGS.indexOf(peek()) >= 0) { 2570 flags += advance(); 2571 } 2572 // Width 2573 if (width == null && nextIsInt()) { 2574 width = nextInt(); 2575 } 2576 // Precision 2577 if (peek() == '.') { 2578 advance(); 2579 if (!nextIsInt()) { 2580 throw new IllegalFormatPrecisionException(peek()); 2581 } 2582 precision = nextInt(); 2583 } 2584 // tT 2585 if (peek() == 't' || peek() == 'T') { 2586 tT = String.valueOf(advance()); 2587 } 2588 // Conversion 2589 conv = String.valueOf(advance()); 2590 2591 fs = new FormatSpecifier(index, flags, width, precision, tT, conv); 2592 } 2593 2594 private String nextInt() { 2595 int strBegin = cursor; 2596 while (nextIsInt()) { 2597 advance(); 2598 } 2599 return format.substring(strBegin, cursor); 2600 } 2601 2602 private boolean nextIsInt() { 2603 return !isEnd() && Character.isDigit(peek()); 2604 } 2605 2606 private char peek() { 2607 if (isEnd()) { 2608 throw new UnknownFormatConversionException("End of String"); 2609 } 2610 return format.charAt(cursor); 2611 } 2612 2613 private char advance() { 2614 if (isEnd()) { 2615 throw new UnknownFormatConversionException("End of String"); 2616 } 2617 return format.charAt(cursor++); 2618 } 2619 2620 private void back(int len) { 2621 cursor -= len; 2622 } 2623 2624 private boolean isEnd() { 2625 return cursor == format.length(); 2626 } 2627 2628 public FormatSpecifier getFormatSpecifier() { 2629 return fs; 2630 } 2631 2632 public int getEndIdx() { 2633 return cursor; 2634 } 2635 } 2636 2637 private interface FormatString { 2638 int index(); 2639 void print(Object arg, Locale l) throws IOException; 2640 String toString(); 2641 } 2642 2643 private class FixedString implements FormatString { 2644 private String s; 2645 FixedString(String s) { this.s = s; } 2646 public int index() { return -2; } 2647 public void print(Object arg, Locale l) 2648 throws IOException { a.append(s); } 2649 public String toString() { return s; } 2650 } 2651 2652 public enum BigDecimalLayoutForm { SCIENTIFIC, DECIMAL_FLOAT }; 2653 2654 private class FormatSpecifier implements FormatString { 2655 private int index = -1; 2656 private Flags f = Flags.NONE; 2657 private int width; 2658 private int precision; 2659 private boolean dt = false; 2660 private char c; 2661 2662 private int index(String s) { 2663 if (s != null) { 2664 try { 2665 index = Integer.parseInt(s); 2666 } catch (NumberFormatException x) { 2667 assert(false); 2668 } 2669 } else { 2670 index = 0; 2671 } 2672 return index; 2673 } 2674 2675 public int index() { 2676 return index; 2677 } 2678 2679 private Flags flags(String s) { 2680 f = Flags.parse(s); 2681 if (f.contains(Flags.PREVIOUS)) 2682 index = -1; 2683 return f; 2684 } 2685 2686 Flags flags() { 2687 return f; 2688 } 2689 2690 private int width(String s) { 2691 width = -1; 2692 if (s != null) { 2693 try { 2694 width = Integer.parseInt(s); 2695 if (width < 0) 2696 throw new IllegalFormatWidthException(width); 2697 } catch (NumberFormatException x) { 2698 assert(false); 2699 } 2700 } 2701 return width; 2702 } 2703 2704 int width() { 2705 return width; 2706 } 2707 2708 private int precision(String s) { 2709 precision = -1; 2710 if (s != null) { 2711 try { 2712 precision = Integer.parseInt(s); 2713 if (precision < 0) 2714 throw new IllegalFormatPrecisionException(precision); 2715 } catch (NumberFormatException x) { 2716 assert(false); 2717 } 2718 } 2719 return precision; 2720 } 2721 2722 int precision() { 2723 return precision; 2724 } 2725 2726 private char conversion(String s) { 2727 c = s.charAt(0); 2728 if (!dt) { 2729 if (!Conversion.isValid(c)) 2730 throw new UnknownFormatConversionException(String.valueOf(c)); 2731 if (Character.isUpperCase(c)) 2732 f.add(Flags.UPPERCASE); 2733 c = Character.toLowerCase(c); 2734 if (Conversion.isText(c)) 2735 index = -2; 2736 } 2737 return c; 2738 } 2739 2740 private char conversion() { 2741 return c; 2742 } 2743 2744 FormatSpecifier(String indexStr, String flagsStr, String widthStr, 2745 String precisionStr, String tTStr, String convStr) { 2746 int idx = 1; 2747 2748 index(indexStr); 2749 flags(flagsStr); 2750 width(widthStr); 2751 precision(precisionStr); 2752 2753 if (tTStr != null) { 2754 dt = true; 2755 if (tTStr.equals("T")) 2756 f.add(Flags.UPPERCASE); 2757 } 2758 2759 conversion(convStr); 2760 2761 if (dt) 2762 checkDateTime(); 2763 else if (Conversion.isGeneral(c)) 2764 checkGeneral(); 2765 else if (Conversion.isCharacter(c)) 2766 checkCharacter(); 2767 else if (Conversion.isInteger(c)) 2768 checkInteger(); 2769 else if (Conversion.isFloat(c)) 2770 checkFloat(); 2771 else if (Conversion.isText(c)) 2772 checkText(); 2773 else 2774 throw new UnknownFormatConversionException(String.valueOf(c)); 2775 } 2776 2777 public void print(Object arg, Locale l) throws IOException { 2778 if (dt) { 2779 printDateTime(arg, l); 2780 return; 2781 } 2782 switch(c) { 2783 case Conversion.DECIMAL_INTEGER: 2784 case Conversion.OCTAL_INTEGER: 2785 case Conversion.HEXADECIMAL_INTEGER: 2786 printInteger(arg, l); 2787 break; 2788 case Conversion.SCIENTIFIC: 2789 case Conversion.GENERAL: 2790 case Conversion.DECIMAL_FLOAT: 2791 case Conversion.HEXADECIMAL_FLOAT: 2792 printFloat(arg, l); 2793 break; 2794 case Conversion.CHARACTER: 2795 case Conversion.CHARACTER_UPPER: 2796 printCharacter(arg); 2797 break; 2798 case Conversion.BOOLEAN: 2799 printBoolean(arg); 2800 break; 2801 case Conversion.STRING: 2802 printString(arg, l); 2803 break; 2804 case Conversion.HASHCODE: 2805 printHashCode(arg); 2806 break; 2807 case Conversion.LINE_SEPARATOR: 2808 a.append(System.lineSeparator()); 2809 break; 2810 case Conversion.PERCENT_SIGN: 2811 a.append('%'); 2812 break; 2813 default: 2814 assert false; 2815 } 2816 } 2817 2818 private void printInteger(Object arg, Locale l) throws IOException { 2819 if (arg == null) 2820 print("null"); 2821 else if (arg instanceof Byte) 2822 print(((Byte)arg).byteValue(), l); 2823 else if (arg instanceof Short) 2824 print(((Short)arg).shortValue(), l); 2825 else if (arg instanceof Integer) 2826 print(((Integer)arg).intValue(), l); 2827 else if (arg instanceof Long) 2828 print(((Long)arg).longValue(), l); 2829 else if (arg instanceof BigInteger) 2830 print(((BigInteger)arg), l); 2831 else 2832 failConversion(c, arg); 2833 } 2834 2835 private void printFloat(Object arg, Locale l) throws IOException { 2836 if (arg == null) 2837 print("null"); 2838 else if (arg instanceof Float) 2839 print(((Float)arg).floatValue(), l); 2840 else if (arg instanceof Double) 2841 print(((Double)arg).doubleValue(), l); 2842 else if (arg instanceof BigDecimal) 2843 print(((BigDecimal)arg), l); 2844 else 2845 failConversion(c, arg); 2846 } 2847 2848 private void printDateTime(Object arg, Locale l) throws IOException { 2849 if (arg == null) { 2850 print("null"); 2851 return; 2852 } 2853 Calendar cal = null; 2854 2855 // Instead of Calendar.setLenient(true), perhaps we should 2856 // wrap the IllegalArgumentException that might be thrown? 2857 if (arg instanceof Long) { 2858 // Note that the following method uses an instance of the 2859 // default time zone (TimeZone.getDefaultRef(). 2860 cal = Calendar.getInstance(l == null ? Locale.US : l); 2861 cal.setTimeInMillis((Long)arg); 2862 } else if (arg instanceof Date) { 2863 // Note that the following method uses an instance of the 2864 // default time zone (TimeZone.getDefaultRef(). 2865 cal = Calendar.getInstance(l == null ? Locale.US : l); 2866 cal.setTime((Date)arg); 2867 } else if (arg instanceof Calendar) { 2868 cal = (Calendar) ((Calendar)arg).clone(); 2869 cal.setLenient(true); 2870 } else { 2871 failConversion(c, arg); 2872 } 2873 // Use the provided locale so that invocations of 2874 // localizedMagnitude() use optimizations for null. 2875 print(cal, c, l); 2876 } 2877 2878 private void printCharacter(Object arg) throws IOException { 2879 if (arg == null) { 2880 print("null"); 2881 return; 2882 } 2883 String s = null; 2884 if (arg instanceof Character) { 2885 s = ((Character)arg).toString(); 2886 } else if (arg instanceof Byte) { 2887 byte i = ((Byte)arg).byteValue(); 2888 if (Character.isValidCodePoint(i)) 2889 s = new String(Character.toChars(i)); 2890 else 2891 throw new IllegalFormatCodePointException(i); 2892 } else if (arg instanceof Short) { 2893 short i = ((Short)arg).shortValue(); 2894 if (Character.isValidCodePoint(i)) 2895 s = new String(Character.toChars(i)); 2896 else 2897 throw new IllegalFormatCodePointException(i); 2898 } else if (arg instanceof Integer) { 2899 int i = ((Integer)arg).intValue(); 2900 if (Character.isValidCodePoint(i)) 2901 s = new String(Character.toChars(i)); 2902 else 2903 throw new IllegalFormatCodePointException(i); 2904 } else { 2905 failConversion(c, arg); 2906 } 2907 print(s); 2908 } 2909 2910 private void printString(Object arg, Locale l) throws IOException { 2911 if (arg instanceof Formattable) { 2912 Formatter fmt = Formatter.this; 2913 if (fmt.locale() != l) 2914 fmt = new Formatter(fmt.out(), l); 2915 ((Formattable)arg).formatTo(fmt, f.valueOf(), width, precision); 2916 } else { 2917 if (f.contains(Flags.ALTERNATE)) 2918 failMismatch(Flags.ALTERNATE, 's'); 2919 if (arg == null) 2920 print("null"); 2921 else 2922 print(arg.toString()); 2923 } 2924 } 2925 2926 private void printBoolean(Object arg) throws IOException { 2927 String s; 2928 if (arg != null) 2929 s = ((arg instanceof Boolean) 2930 ? ((Boolean)arg).toString() 2931 : Boolean.toString(true)); 2932 else 2933 s = Boolean.toString(false); 2934 print(s); 2935 } 2936 2937 private void printHashCode(Object arg) throws IOException { 2938 String s = (arg == null 2939 ? "null" 2940 : Integer.toHexString(arg.hashCode())); 2941 print(s); 2942 } 2943 2944 private void print(String s) throws IOException { 2945 if (precision != -1 && precision < s.length()) 2946 s = s.substring(0, precision); 2947 if (f.contains(Flags.UPPERCASE)) { 2948 // Always uppercase strings according to the provided locale. 2949 s = s.toUpperCase(l != null ? l : Locale.getDefault()); 2950 } 2951 a.append(justify(s)); 2952 } 2953 2954 private String justify(String s) { 2955 if (width == -1) 2956 return s; 2957 StringBuilder sb = new StringBuilder(); 2958 boolean pad = f.contains(Flags.LEFT_JUSTIFY); 2959 int sp = width - s.length(); 2960 if (!pad) 2961 for (int i = 0; i < sp; i++) sb.append(' '); 2962 sb.append(s); 2963 if (pad) 2964 for (int i = 0; i < sp; i++) sb.append(' '); 2965 return sb.toString(); 2966 } 2967 2968 public String toString() { 2969 StringBuilder sb = new StringBuilder("%"); 2970 // Flags.UPPERCASE is set internally for legal conversions. 2971 Flags dupf = f.dup().remove(Flags.UPPERCASE); 2972 sb.append(dupf.toString()); 2973 if (index > 0) 2974 sb.append(index).append('$'); 2975 if (width != -1) 2976 sb.append(width); 2977 if (precision != -1) 2978 sb.append('.').append(precision); 2979 if (dt) 2980 sb.append(f.contains(Flags.UPPERCASE) ? 'T' : 't'); 2981 sb.append(f.contains(Flags.UPPERCASE) 2982 ? Character.toUpperCase(c) : c); 2983 return sb.toString(); 2984 } 2985 2986 private void checkGeneral() { 2987 if ((c == Conversion.BOOLEAN || c == Conversion.HASHCODE) 2988 && f.contains(Flags.ALTERNATE)) 2989 failMismatch(Flags.ALTERNATE, c); 2990 // '-' requires a width 2991 if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) 2992 throw new MissingFormatWidthException(toString()); 2993 checkBadFlags(Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD, 2994 Flags.GROUP, Flags.PARENTHESES); 2995 } 2996 2997 private void checkDateTime() { 2998 if (precision != -1) 2999 throw new IllegalFormatPrecisionException(precision); 3000 if (!DateTime.isValid(c)) 3001 throw new UnknownFormatConversionException("t" + c); 3002 checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE, 3003 Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES); 3004 // '-' requires a width 3005 if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) 3006 throw new MissingFormatWidthException(toString()); 3007 } 3008 3009 private void checkCharacter() { 3010 if (precision != -1) 3011 throw new IllegalFormatPrecisionException(precision); 3012 checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE, 3013 Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES); 3014 // '-' requires a width 3015 if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) 3016 throw new MissingFormatWidthException(toString()); 3017 } 3018 3019 private void checkInteger() { 3020 checkNumeric(); 3021 if (precision != -1) 3022 throw new IllegalFormatPrecisionException(precision); 3023 3024 if (c == Conversion.DECIMAL_INTEGER) 3025 checkBadFlags(Flags.ALTERNATE); 3026 else if (c == Conversion.OCTAL_INTEGER) 3027 checkBadFlags(Flags.GROUP); 3028 else 3029 checkBadFlags(Flags.GROUP); 3030 } 3031 3032 private void checkBadFlags(Flags ... badFlags) { 3033 for (int i = 0; i < badFlags.length; i++) 3034 if (f.contains(badFlags[i])) 3035 failMismatch(badFlags[i], c); 3036 } 3037 3038 private void checkFloat() { 3039 checkNumeric(); 3040 if (c == Conversion.DECIMAL_FLOAT) { 3041 } else if (c == Conversion.HEXADECIMAL_FLOAT) { 3042 checkBadFlags(Flags.PARENTHESES, Flags.GROUP); 3043 } else if (c == Conversion.SCIENTIFIC) { 3044 checkBadFlags(Flags.GROUP); 3045 } else if (c == Conversion.GENERAL) { 3046 checkBadFlags(Flags.ALTERNATE); 3047 } 3048 } 3049 3050 private void checkNumeric() { 3051 if (width != -1 && width < 0) 3052 throw new IllegalFormatWidthException(width); 3053 3054 if (precision != -1 && precision < 0) 3055 throw new IllegalFormatPrecisionException(precision); 3056 3057 // '-' and '0' require a width 3058 if (width == -1 3059 && (f.contains(Flags.LEFT_JUSTIFY) || f.contains(Flags.ZERO_PAD))) 3060 throw new MissingFormatWidthException(toString()); 3061 3062 // bad combination 3063 if ((f.contains(Flags.PLUS) && f.contains(Flags.LEADING_SPACE)) 3064 || (f.contains(Flags.LEFT_JUSTIFY) && f.contains(Flags.ZERO_PAD))) 3065 throw new IllegalFormatFlagsException(f.toString()); 3066 } 3067 3068 private void checkText() { 3069 if (precision != -1) 3070 throw new IllegalFormatPrecisionException(precision); 3071 switch (c) { 3072 case Conversion.PERCENT_SIGN: 3073 if (f.valueOf() != Flags.LEFT_JUSTIFY.valueOf() 3074 && f.valueOf() != Flags.NONE.valueOf()) 3075 throw new IllegalFormatFlagsException(f.toString()); 3076 // '-' requires a width 3077 if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) 3078 throw new MissingFormatWidthException(toString()); 3079 break; 3080 case Conversion.LINE_SEPARATOR: 3081 if (width != -1) 3082 throw new IllegalFormatWidthException(width); 3083 if (f.valueOf() != Flags.NONE.valueOf()) 3084 throw new IllegalFormatFlagsException(f.toString()); 3085 break; 3086 default: 3087 assert false; 3088 } 3089 } 3090 3091 private void print(byte value, Locale l) throws IOException { 3092 long v = value; 3093 if (value < 0 3094 && (c == Conversion.OCTAL_INTEGER 3095 || c == Conversion.HEXADECIMAL_INTEGER)) { 3096 v += (1L << 8); 3097 assert v >= 0 : v; 3098 } 3099 print(v, l); 3100 } 3101 3102 private void print(short value, Locale l) throws IOException { 3103 long v = value; 3104 if (value < 0 3105 && (c == Conversion.OCTAL_INTEGER 3106 || c == Conversion.HEXADECIMAL_INTEGER)) { 3107 v += (1L << 16); 3108 assert v >= 0 : v; 3109 } 3110 print(v, l); 3111 } 3112 3113 private void print(int value, Locale l) throws IOException { 3114 long v = value; 3115 if (value < 0 3116 && (c == Conversion.OCTAL_INTEGER 3117 || c == Conversion.HEXADECIMAL_INTEGER)) { 3118 v += (1L << 32); 3119 assert v >= 0 : v; 3120 } 3121 print(v, l); 3122 } 3123 3124 private void print(long value, Locale l) throws IOException { 3125 3126 StringBuilder sb = new StringBuilder(); 3127 3128 if (c == Conversion.DECIMAL_INTEGER) { 3129 boolean neg = value < 0; 3130 char[] va; 3131 if (value < 0) 3132 va = Long.toString(value, 10).substring(1).toCharArray(); 3133 else 3134 va = Long.toString(value, 10).toCharArray(); 3135 3136 // leading sign indicator 3137 leadingSign(sb, neg); 3138 3139 // the value 3140 localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l); 3141 3142 // trailing sign indicator 3143 trailingSign(sb, neg); 3144 } else if (c == Conversion.OCTAL_INTEGER) { 3145 checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE, 3146 Flags.PLUS); 3147 String s = Long.toOctalString(value); 3148 int len = (f.contains(Flags.ALTERNATE) 3149 ? s.length() + 1 3150 : s.length()); 3151 3152 // apply ALTERNATE (radix indicator for octal) before ZERO_PAD 3153 if (f.contains(Flags.ALTERNATE)) 3154 sb.append('0'); 3155 if (f.contains(Flags.ZERO_PAD)) 3156 for (int i = 0; i < width - len; i++) sb.append('0'); 3157 sb.append(s); 3158 } else if (c == Conversion.HEXADECIMAL_INTEGER) { 3159 checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE, 3160 Flags.PLUS); 3161 String s = Long.toHexString(value); 3162 int len = (f.contains(Flags.ALTERNATE) 3163 ? s.length() + 2 3164 : s.length()); 3165 3166 // apply ALTERNATE (radix indicator for hex) before ZERO_PAD 3167 if (f.contains(Flags.ALTERNATE)) 3168 sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x"); 3169 if (f.contains(Flags.ZERO_PAD)) 3170 for (int i = 0; i < width - len; i++) sb.append('0'); 3171 if (f.contains(Flags.UPPERCASE)) 3172 s = s.toUpperCase(); 3173 sb.append(s); 3174 } 3175 3176 // justify based on width 3177 a.append(justify(sb.toString())); 3178 } 3179 3180 // neg := val < 0 3181 private StringBuilder leadingSign(StringBuilder sb, boolean neg) { 3182 if (!neg) { 3183 if (f.contains(Flags.PLUS)) { 3184 sb.append('+'); 3185 } else if (f.contains(Flags.LEADING_SPACE)) { 3186 sb.append(' '); 3187 } 3188 } else { 3189 if (f.contains(Flags.PARENTHESES)) 3190 sb.append('('); 3191 else 3192 sb.append('-'); 3193 } 3194 return sb; 3195 } 3196 3197 // neg := val < 0 3198 private StringBuilder trailingSign(StringBuilder sb, boolean neg) { 3199 if (neg && f.contains(Flags.PARENTHESES)) 3200 sb.append(')'); 3201 return sb; 3202 } 3203 3204 private void print(BigInteger value, Locale l) throws IOException { 3205 StringBuilder sb = new StringBuilder(); 3206 boolean neg = value.signum() == -1; 3207 BigInteger v = value.abs(); 3208 3209 // leading sign indicator 3210 leadingSign(sb, neg); 3211 3212 // the value 3213 if (c == Conversion.DECIMAL_INTEGER) { 3214 char[] va = v.toString().toCharArray(); 3215 localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l); 3216 } else if (c == Conversion.OCTAL_INTEGER) { 3217 String s = v.toString(8); 3218 3219 int len = s.length() + sb.length(); 3220 if (neg && f.contains(Flags.PARENTHESES)) 3221 len++; 3222 3223 // apply ALTERNATE (radix indicator for octal) before ZERO_PAD 3224 if (f.contains(Flags.ALTERNATE)) { 3225 len++; 3226 sb.append('0'); 3227 } 3228 if (f.contains(Flags.ZERO_PAD)) { 3229 for (int i = 0; i < width - len; i++) 3230 sb.append('0'); 3231 } 3232 sb.append(s); 3233 } else if (c == Conversion.HEXADECIMAL_INTEGER) { 3234 String s = v.toString(16); 3235 3236 int len = s.length() + sb.length(); 3237 if (neg && f.contains(Flags.PARENTHESES)) 3238 len++; 3239 3240 // apply ALTERNATE (radix indicator for hex) before ZERO_PAD 3241 if (f.contains(Flags.ALTERNATE)) { 3242 len += 2; 3243 sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x"); 3244 } 3245 if (f.contains(Flags.ZERO_PAD)) 3246 for (int i = 0; i < width - len; i++) 3247 sb.append('0'); 3248 if (f.contains(Flags.UPPERCASE)) 3249 s = s.toUpperCase(); 3250 sb.append(s); 3251 } 3252 3253 // trailing sign indicator 3254 trailingSign(sb, (value.signum() == -1)); 3255 3256 // justify based on width 3257 a.append(justify(sb.toString())); 3258 } 3259 3260 private void print(float value, Locale l) throws IOException { 3261 print((double) value, l); 3262 } 3263 3264 private void print(double value, Locale l) throws IOException { 3265 StringBuilder sb = new StringBuilder(); 3266 boolean neg = Double.compare(value, 0.0) == -1; 3267 3268 if (!Double.isNaN(value)) { 3269 double v = Math.abs(value); 3270 3271 // leading sign indicator 3272 leadingSign(sb, neg); 3273 3274 // the value 3275 if (!Double.isInfinite(v)) 3276 print(sb, v, l, f, c, precision, neg); 3277 else 3278 sb.append(f.contains(Flags.UPPERCASE) 3279 ? "INFINITY" : "Infinity"); 3280 3281 // trailing sign indicator 3282 trailingSign(sb, neg); 3283 } else { 3284 sb.append(f.contains(Flags.UPPERCASE) ? "NAN" : "NaN"); 3285 } 3286 3287 // justify based on width 3288 a.append(justify(sb.toString())); 3289 } 3290 3291 // !Double.isInfinite(value) && !Double.isNaN(value) 3292 private void print(StringBuilder sb, double value, Locale l, 3293 Flags f, char c, int precision, boolean neg) 3294 throws IOException 3295 { 3296 if (c == Conversion.SCIENTIFIC) { 3297 // Create a new FormattedFloatingDecimal with the desired 3298 // precision. 3299 int prec = (precision == -1 ? 6 : precision); 3300 3301 FormattedFloatingDecimal fd 3302 = FormattedFloatingDecimal.valueOf(value, prec, 3303 FormattedFloatingDecimal.Form.SCIENTIFIC); 3304 3305 char[] mant = addZeros(fd.getMantissa(), prec); 3306 3307 // If the precision is zero and the '#' flag is set, add the 3308 // requested decimal point. 3309 if (f.contains(Flags.ALTERNATE) && (prec == 0)) 3310 mant = addDot(mant); 3311 3312 char[] exp = (value == 0.0) 3313 ? new char[] {'+','0','0'} : fd.getExponent(); 3314 3315 int newW = width; 3316 if (width != -1) 3317 newW = adjustWidth(width - exp.length - 1, f, neg); 3318 localizedMagnitude(sb, mant, f, newW, l); 3319 3320 Locale separatorLocale = (l != null) ? l : Locale.getDefault(); 3321 LocaleData localeData = LocaleData.get(separatorLocale); 3322 sb.append(f.contains(Flags.UPPERCASE) ? 3323 localeData.exponentSeparator.toUpperCase(separatorLocale) : 3324 localeData.exponentSeparator.toLowerCase(separatorLocale)); 3325 3326 Flags flags = f.dup().remove(Flags.GROUP); 3327 char sign = exp[0]; 3328 assert(sign == '+' || sign == '-'); 3329 sb.append(sign); 3330 3331 char[] tmp = new char[exp.length - 1]; 3332 System.arraycopy(exp, 1, tmp, 0, exp.length - 1); 3333 sb.append(localizedMagnitude(null, tmp, flags, -1, l)); 3334 } else if (c == Conversion.DECIMAL_FLOAT) { 3335 // Create a new FormattedFloatingDecimal with the desired 3336 // precision. 3337 int prec = (precision == -1 ? 6 : precision); 3338 3339 FormattedFloatingDecimal fd 3340 = FormattedFloatingDecimal.valueOf(value, prec, 3341 FormattedFloatingDecimal.Form.DECIMAL_FLOAT); 3342 3343 char[] mant = addZeros(fd.getMantissa(), prec); 3344 3345 // If the precision is zero and the '#' flag is set, add the 3346 // requested decimal point. 3347 if (f.contains(Flags.ALTERNATE) && (prec == 0)) 3348 mant = addDot(mant); 3349 3350 int newW = width; 3351 if (width != -1) 3352 newW = adjustWidth(width, f, neg); 3353 localizedMagnitude(sb, mant, f, newW, l); 3354 } else if (c == Conversion.GENERAL) { 3355 int prec = precision; 3356 if (precision == -1) 3357 prec = 6; 3358 else if (precision == 0) 3359 prec = 1; 3360 3361 char[] exp; 3362 char[] mant; 3363 int expRounded; 3364 if (value == 0.0) { 3365 exp = null; 3366 mant = new char[] {'0'}; 3367 expRounded = 0; 3368 } else { 3369 FormattedFloatingDecimal fd 3370 = FormattedFloatingDecimal.valueOf(value, prec, 3371 FormattedFloatingDecimal.Form.GENERAL); 3372 exp = fd.getExponent(); 3373 mant = fd.getMantissa(); 3374 expRounded = fd.getExponentRounded(); 3375 } 3376 3377 if (exp != null) { 3378 prec -= 1; 3379 } else { 3380 prec -= expRounded + 1; 3381 } 3382 3383 mant = addZeros(mant, prec); 3384 // If the precision is zero and the '#' flag is set, add the 3385 // requested decimal point. 3386 if (f.contains(Flags.ALTERNATE) && (prec == 0)) 3387 mant = addDot(mant); 3388 3389 int newW = width; 3390 if (width != -1) { 3391 if (exp != null) 3392 newW = adjustWidth(width - exp.length - 1, f, neg); 3393 else 3394 newW = adjustWidth(width, f, neg); 3395 } 3396 localizedMagnitude(sb, mant, f, newW, l); 3397 3398 if (exp != null) { 3399 sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e'); 3400 3401 Flags flags = f.dup().remove(Flags.GROUP); 3402 char sign = exp[0]; 3403 assert(sign == '+' || sign == '-'); 3404 sb.append(sign); 3405 3406 char[] tmp = new char[exp.length - 1]; 3407 System.arraycopy(exp, 1, tmp, 0, exp.length - 1); 3408 sb.append(localizedMagnitude(null, tmp, flags, -1, l)); 3409 } 3410 } else if (c == Conversion.HEXADECIMAL_FLOAT) { 3411 int prec = precision; 3412 if (precision == -1) 3413 // assume that we want all of the digits 3414 prec = 0; 3415 else if (precision == 0) 3416 prec = 1; 3417 3418 String s = hexDouble(value, prec); 3419 3420 char[] va; 3421 boolean upper = f.contains(Flags.UPPERCASE); 3422 sb.append(upper ? "0X" : "0x"); 3423 3424 if (f.contains(Flags.ZERO_PAD)) 3425 for (int i = 0; i < width - s.length() - 2; i++) 3426 sb.append('0'); 3427 3428 int idx = s.indexOf('p'); 3429 va = s.substring(0, idx).toCharArray(); 3430 if (upper) { 3431 String tmp = new String(va); 3432 // don't localize hex 3433 tmp = tmp.toUpperCase(Locale.US); 3434 va = tmp.toCharArray(); 3435 } 3436 sb.append(prec != 0 ? addZeros(va, prec) : va); 3437 sb.append(upper ? 'P' : 'p'); 3438 sb.append(s.substring(idx+1)); 3439 } 3440 } 3441 3442 private char[] mantissa(char[] v, int len) { 3443 int i; 3444 for (i = 0; i < len; i++) { 3445 if (v[i] == 'e') 3446 break; 3447 } 3448 char[] tmp = new char[i]; 3449 System.arraycopy(v, 0, tmp, 0, i); 3450 return tmp; 3451 } 3452 3453 private char[] exponent(char[] v, int len) { 3454 int i; 3455 for (i = len - 1; i >= 0; i--) { 3456 if (v[i] == 'e') 3457 break; 3458 } 3459 if (i == -1) 3460 return null; 3461 char[] tmp = new char[len - i - 1]; 3462 System.arraycopy(v, i + 1, tmp, 0, len - i - 1); 3463 return tmp; 3464 } 3465 3466 // Add zeros to the requested precision. 3467 private char[] addZeros(char[] v, int prec) { 3468 // Look for the dot. If we don't find one, the we'll need to add 3469 // it before we add the zeros. 3470 int i; 3471 for (i = 0; i < v.length; i++) { 3472 if (v[i] == '.') 3473 break; 3474 } 3475 boolean needDot = false; 3476 if (i == v.length) { 3477 needDot = true; 3478 } 3479 3480 // Determine existing precision. 3481 int outPrec = v.length - i - (needDot ? 0 : 1); 3482 assert (outPrec <= prec); 3483 if (outPrec == prec) 3484 return v; 3485 3486 // Create new array with existing contents. 3487 char[] tmp 3488 = new char[v.length + prec - outPrec + (needDot ? 1 : 0)]; 3489 System.arraycopy(v, 0, tmp, 0, v.length); 3490 3491 // Add dot if previously determined to be necessary. 3492 int start = v.length; 3493 if (needDot) { 3494 tmp[v.length] = '.'; 3495 start++; 3496 } 3497 3498 // Add zeros. 3499 for (int j = start; j < tmp.length; j++) 3500 tmp[j] = '0'; 3501 3502 return tmp; 3503 } 3504 3505 // Method assumes that d > 0. 3506 private String hexDouble(double d, int prec) { 3507 // Let Double.toHexString handle simple cases 3508 if(!FpUtils.isFinite(d) || d == 0.0 || prec == 0 || prec >= 13) 3509 // remove "0x" 3510 return Double.toHexString(d).substring(2); 3511 else { 3512 assert(prec >= 1 && prec <= 12); 3513 3514 int exponent = FpUtils.getExponent(d); 3515 boolean subnormal 3516 = (exponent == DoubleConsts.MIN_EXPONENT - 1); 3517 3518 // If this is subnormal input so normalize (could be faster to 3519 // do as integer operation). 3520 if (subnormal) { 3521 scaleUp = FpUtils.scalb(1.0, 54); 3522 d *= scaleUp; 3523 // Calculate the exponent. This is not just exponent + 54 3524 // since the former is not the normalized exponent. 3525 exponent = FpUtils.getExponent(d); 3526 assert exponent >= DoubleConsts.MIN_EXPONENT && 3527 exponent <= DoubleConsts.MAX_EXPONENT: exponent; 3528 } 3529 3530 int precision = 1 + prec*4; 3531 int shiftDistance 3532 = DoubleConsts.SIGNIFICAND_WIDTH - precision; 3533 assert(shiftDistance >= 1 && shiftDistance < DoubleConsts.SIGNIFICAND_WIDTH); 3534 3535 long doppel = Double.doubleToLongBits(d); 3536 // Deterime the number of bits to keep. 3537 long newSignif 3538 = (doppel & (DoubleConsts.EXP_BIT_MASK 3539 | DoubleConsts.SIGNIF_BIT_MASK)) 3540 >> shiftDistance; 3541 // Bits to round away. 3542 long roundingBits = doppel & ~(~0L << shiftDistance); 3543 3544 // To decide how to round, look at the low-order bit of the 3545 // working significand, the highest order discarded bit (the 3546 // round bit) and whether any of the lower order discarded bits 3547 // are nonzero (the sticky bit). 3548 3549 boolean leastZero = (newSignif & 0x1L) == 0L; 3550 boolean round 3551 = ((1L << (shiftDistance - 1) ) & roundingBits) != 0L; 3552 boolean sticky = shiftDistance > 1 && 3553 (~(1L<< (shiftDistance - 1)) & roundingBits) != 0; 3554 if((leastZero && round && sticky) || (!leastZero && round)) { 3555 newSignif++; 3556 } 3557 3558 long signBit = doppel & DoubleConsts.SIGN_BIT_MASK; 3559 newSignif = signBit | (newSignif << shiftDistance); 3560 double result = Double.longBitsToDouble(newSignif); 3561 3562 if (Double.isInfinite(result) ) { 3563 // Infinite result generated by rounding 3564 return "1.0p1024"; 3565 } else { 3566 String res = Double.toHexString(result).substring(2); 3567 if (!subnormal) 3568 return res; 3569 else { 3570 // Create a normalized subnormal string. 3571 int idx = res.indexOf('p'); 3572 if (idx == -1) { 3573 // No 'p' character in hex string. 3574 assert false; 3575 return null; 3576 } else { 3577 // Get exponent and append at the end. 3578 String exp = res.substring(idx + 1); 3579 int iexp = Integer.parseInt(exp) -54; 3580 return res.substring(0, idx) + "p" 3581 + Integer.toString(iexp); 3582 } 3583 } 3584 } 3585 } 3586 } 3587 3588 private void print(BigDecimal value, Locale l) throws IOException { 3589 if (c == Conversion.HEXADECIMAL_FLOAT) 3590 failConversion(c, value); 3591 StringBuilder sb = new StringBuilder(); 3592 boolean neg = value.signum() == -1; 3593 BigDecimal v = value.abs(); 3594 // leading sign indicator 3595 leadingSign(sb, neg); 3596 3597 // the value 3598 print(sb, v, l, f, c, precision, neg); 3599 3600 // trailing sign indicator 3601 trailingSign(sb, neg); 3602 3603 // justify based on width 3604 a.append(justify(sb.toString())); 3605 } 3606 3607 // value > 0 3608 private void print(StringBuilder sb, BigDecimal value, Locale l, 3609 Flags f, char c, int precision, boolean neg) 3610 throws IOException 3611 { 3612 if (c == Conversion.SCIENTIFIC) { 3613 // Create a new BigDecimal with the desired precision. 3614 int prec = (precision == -1 ? 6 : precision); 3615 int scale = value.scale(); 3616 int origPrec = value.precision(); 3617 int nzeros = 0; 3618 int compPrec; 3619 3620 if (prec > origPrec - 1) { 3621 compPrec = origPrec; 3622 nzeros = prec - (origPrec - 1); 3623 } else { 3624 compPrec = prec + 1; 3625 } 3626 3627 MathContext mc = new MathContext(compPrec); 3628 BigDecimal v 3629 = new BigDecimal(value.unscaledValue(), scale, mc); 3630 3631 BigDecimalLayout bdl 3632 = new BigDecimalLayout(v.unscaledValue(), v.scale(), 3633 BigDecimalLayoutForm.SCIENTIFIC); 3634 3635 char[] mant = bdl.mantissa(); 3636 3637 // Add a decimal point if necessary. The mantissa may not 3638 // contain a decimal point if the scale is zero (the internal 3639 // representation has no fractional part) or the original 3640 // precision is one. Append a decimal point if '#' is set or if 3641 // we require zero padding to get to the requested precision. 3642 if ((origPrec == 1 || !bdl.hasDot()) 3643 && (nzeros > 0 || (f.contains(Flags.ALTERNATE)))) 3644 mant = addDot(mant); 3645 3646 // Add trailing zeros in the case precision is greater than 3647 // the number of available digits after the decimal separator. 3648 mant = trailingZeros(mant, nzeros); 3649 3650 char[] exp = bdl.exponent(); 3651 int newW = width; 3652 if (width != -1) 3653 newW = adjustWidth(width - exp.length - 1, f, neg); 3654 localizedMagnitude(sb, mant, f, newW, l); 3655 3656 sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e'); 3657 3658 Flags flags = f.dup().remove(Flags.GROUP); 3659 char sign = exp[0]; 3660 assert(sign == '+' || sign == '-'); 3661 sb.append(exp[0]); 3662 3663 char[] tmp = new char[exp.length - 1]; 3664 System.arraycopy(exp, 1, tmp, 0, exp.length - 1); 3665 sb.append(localizedMagnitude(null, tmp, flags, -1, l)); 3666 } else if (c == Conversion.DECIMAL_FLOAT) { 3667 // Create a new BigDecimal with the desired precision. 3668 int prec = (precision == -1 ? 6 : precision); 3669 int scale = value.scale(); 3670 3671 if (scale > prec) { 3672 // more "scale" digits than the requested "precision" 3673 int compPrec = value.precision(); 3674 if (compPrec <= scale) { 3675 // case of 0.xxxxxx 3676 value = value.setScale(prec, RoundingMode.HALF_UP); 3677 } else { 3678 compPrec -= (scale - prec); 3679 value = new BigDecimal(value.unscaledValue(), 3680 scale, 3681 new MathContext(compPrec)); 3682 } 3683 } 3684 BigDecimalLayout bdl = new BigDecimalLayout( 3685 value.unscaledValue(), 3686 value.scale(), 3687 BigDecimalLayoutForm.DECIMAL_FLOAT); 3688 3689 char mant[] = bdl.mantissa(); 3690 int nzeros = (bdl.scale() < prec ? prec - bdl.scale() : 0); 3691 3692 // Add a decimal point if necessary. The mantissa may not 3693 // contain a decimal point if the scale is zero (the internal 3694 // representation has no fractional part). Append a decimal 3695 // point if '#' is set or we require zero padding to get to the 3696 // requested precision. 3697 if (bdl.scale() == 0 && (f.contains(Flags.ALTERNATE) || nzeros > 0)) 3698 mant = addDot(bdl.mantissa()); 3699 3700 // Add trailing zeros if the precision is greater than the 3701 // number of available digits after the decimal separator. 3702 mant = trailingZeros(mant, nzeros); 3703 3704 localizedMagnitude(sb, mant, f, adjustWidth(width, f, neg), l); 3705 } else if (c == Conversion.GENERAL) { 3706 int prec = precision; 3707 if (precision == -1) 3708 prec = 6; 3709 else if (precision == 0) 3710 prec = 1; 3711 3712 BigDecimal tenToTheNegFour = BigDecimal.valueOf(1, 4); 3713 BigDecimal tenToThePrec = BigDecimal.valueOf(1, -prec); 3714 if ((value.equals(BigDecimal.ZERO)) 3715 || ((value.compareTo(tenToTheNegFour) != -1) 3716 && (value.compareTo(tenToThePrec) == -1))) { 3717 3718 int e = - value.scale() 3719 + (value.unscaledValue().toString().length() - 1); 3720 3721 // xxx.yyy 3722 // g precision (# sig digits) = #x + #y 3723 // f precision = #y 3724 // exponent = #x - 1 3725 // => f precision = g precision - exponent - 1 3726 // 0.000zzz 3727 // g precision (# sig digits) = #z 3728 // f precision = #0 (after '.') + #z 3729 // exponent = - #0 (after '.') - 1 3730 // => f precision = g precision - exponent - 1 3731 prec = prec - e - 1; 3732 3733 print(sb, value, l, f, Conversion.DECIMAL_FLOAT, prec, 3734 neg); 3735 } else { 3736 print(sb, value, l, f, Conversion.SCIENTIFIC, prec - 1, neg); 3737 } 3738 } else if (c == Conversion.HEXADECIMAL_FLOAT) { 3739 // This conversion isn't supported. The error should be 3740 // reported earlier. 3741 assert false; 3742 } 3743 } 3744 3745 private class BigDecimalLayout { 3746 private StringBuilder mant; 3747 private StringBuilder exp; 3748 private boolean dot = false; 3749 private int scale; 3750 3751 public BigDecimalLayout(BigInteger intVal, int scale, BigDecimalLayoutForm form) { 3752 layout(intVal, scale, form); 3753 } 3754 3755 public boolean hasDot() { 3756 return dot; 3757 } 3758 3759 public int scale() { 3760 return scale; 3761 } 3762 3763 // char[] with canonical string representation 3764 public char[] layoutChars() { 3765 StringBuilder sb = new StringBuilder(mant); 3766 if (exp != null) { 3767 sb.append('E'); 3768 sb.append(exp); 3769 } 3770 return toCharArray(sb); 3771 } 3772 3773 public char[] mantissa() { 3774 return toCharArray(mant); 3775 } 3776 3777 // The exponent will be formatted as a sign ('+' or '-') followed 3778 // by the exponent zero-padded to include at least two digits. 3779 public char[] exponent() { 3780 return toCharArray(exp); 3781 } 3782 3783 private char[] toCharArray(StringBuilder sb) { 3784 if (sb == null) 3785 return null; 3786 char[] result = new char[sb.length()]; 3787 sb.getChars(0, result.length, result, 0); 3788 return result; 3789 } 3790 3791 private void layout(BigInteger intVal, int scale, BigDecimalLayoutForm form) { 3792 char coeff[] = intVal.toString().toCharArray(); 3793 this.scale = scale; 3794 3795 // Construct a buffer, with sufficient capacity for all cases. 3796 // If E-notation is needed, length will be: +1 if negative, +1 3797 // if '.' needed, +2 for "E+", + up to 10 for adjusted 3798 // exponent. Otherwise it could have +1 if negative, plus 3799 // leading "0.00000" 3800 mant = new StringBuilder(coeff.length + 14); 3801 3802 if (scale == 0) { 3803 int len = coeff.length; 3804 if (len > 1) { 3805 mant.append(coeff[0]); 3806 if (form == BigDecimalLayoutForm.SCIENTIFIC) { 3807 mant.append('.'); 3808 dot = true; 3809 mant.append(coeff, 1, len - 1); 3810 exp = new StringBuilder("+"); 3811 if (len < 10) 3812 exp.append("0").append(len - 1); 3813 else 3814 exp.append(len - 1); 3815 } else { 3816 mant.append(coeff, 1, len - 1); 3817 } 3818 } else { 3819 mant.append(coeff); 3820 if (form == BigDecimalLayoutForm.SCIENTIFIC) 3821 exp = new StringBuilder("+00"); 3822 } 3823 return; 3824 } 3825 long adjusted = -(long) scale + (coeff.length - 1); 3826 if (form == BigDecimalLayoutForm.DECIMAL_FLOAT) { 3827 // count of padding zeros 3828 int pad = scale - coeff.length; 3829 if (pad >= 0) { 3830 // 0.xxx form 3831 mant.append("0."); 3832 dot = true; 3833 for (; pad > 0 ; pad--) mant.append('0'); 3834 mant.append(coeff); 3835 } else { 3836 if (-pad < coeff.length) { 3837 // xx.xx form 3838 mant.append(coeff, 0, -pad); 3839 mant.append('.'); 3840 dot = true; 3841 mant.append(coeff, -pad, scale); 3842 } else { 3843 // xx form 3844 mant.append(coeff, 0, coeff.length); 3845 for (int i = 0; i < -scale; i++) 3846 mant.append('0'); 3847 this.scale = 0; 3848 } 3849 } 3850 } else { 3851 // x.xxx form 3852 mant.append(coeff[0]); 3853 if (coeff.length > 1) { 3854 mant.append('.'); 3855 dot = true; 3856 mant.append(coeff, 1, coeff.length-1); 3857 } 3858 exp = new StringBuilder(); 3859 if (adjusted != 0) { 3860 long abs = Math.abs(adjusted); 3861 // require sign 3862 exp.append(adjusted < 0 ? '-' : '+'); 3863 if (abs < 10) 3864 exp.append('0'); 3865 exp.append(abs); 3866 } else { 3867 exp.append("+00"); 3868 } 3869 } 3870 } 3871 } 3872 3873 private int adjustWidth(int width, Flags f, boolean neg) { 3874 int newW = width; 3875 if (newW != -1 && neg && f.contains(Flags.PARENTHESES)) 3876 newW--; 3877 return newW; 3878 } 3879 3880 // Add a '.' to th mantissa if required 3881 private char[] addDot(char[] mant) { 3882 char[] tmp = mant; 3883 tmp = new char[mant.length + 1]; 3884 System.arraycopy(mant, 0, tmp, 0, mant.length); 3885 tmp[tmp.length - 1] = '.'; 3886 return tmp; 3887 } 3888 3889 // Add trailing zeros in the case precision is greater than the number 3890 // of available digits after the decimal separator. 3891 private char[] trailingZeros(char[] mant, int nzeros) { 3892 char[] tmp = mant; 3893 if (nzeros > 0) { 3894 tmp = new char[mant.length + nzeros]; 3895 System.arraycopy(mant, 0, tmp, 0, mant.length); 3896 for (int i = mant.length; i < tmp.length; i++) 3897 tmp[i] = '0'; 3898 } 3899 return tmp; 3900 } 3901 3902 private void print(Calendar t, char c, Locale l) throws IOException 3903 { 3904 StringBuilder sb = new StringBuilder(); 3905 print(sb, t, c, l); 3906 3907 // justify based on width 3908 String s = justify(sb.toString()); 3909 if (f.contains(Flags.UPPERCASE)) 3910 s = s.toUpperCase(); 3911 3912 a.append(s); 3913 } 3914 3915 private Appendable print(StringBuilder sb, Calendar t, char c, 3916 Locale l) 3917 throws IOException 3918 { 3919 assert(width == -1); 3920 if (sb == null) 3921 sb = new StringBuilder(); 3922 switch (c) { 3923 case DateTime.HOUR_OF_DAY_0: // 'H' (00 - 23) 3924 case DateTime.HOUR_0: // 'I' (01 - 12) 3925 case DateTime.HOUR_OF_DAY: // 'k' (0 - 23) -- like H 3926 case DateTime.HOUR: { // 'l' (1 - 12) -- like I 3927 int i = t.get(Calendar.HOUR_OF_DAY); 3928 if (c == DateTime.HOUR_0 || c == DateTime.HOUR) 3929 i = (i == 0 || i == 12 ? 12 : i % 12); 3930 Flags flags = (c == DateTime.HOUR_OF_DAY_0 3931 || c == DateTime.HOUR_0 3932 ? Flags.ZERO_PAD 3933 : Flags.NONE); 3934 sb.append(localizedMagnitude(null, i, flags, 2, l)); 3935 break; 3936 } 3937 case DateTime.MINUTE: { // 'M' (00 - 59) 3938 int i = t.get(Calendar.MINUTE); 3939 Flags flags = Flags.ZERO_PAD; 3940 sb.append(localizedMagnitude(null, i, flags, 2, l)); 3941 break; 3942 } 3943 case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999) 3944 int i = t.get(Calendar.MILLISECOND) * 1000000; 3945 Flags flags = Flags.ZERO_PAD; 3946 sb.append(localizedMagnitude(null, i, flags, 9, l)); 3947 break; 3948 } 3949 case DateTime.MILLISECOND: { // 'L' (000 - 999) 3950 int i = t.get(Calendar.MILLISECOND); 3951 Flags flags = Flags.ZERO_PAD; 3952 sb.append(localizedMagnitude(null, i, flags, 3, l)); 3953 break; 3954 } 3955 case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?) 3956 long i = t.getTimeInMillis(); 3957 Flags flags = Flags.NONE; 3958 sb.append(localizedMagnitude(null, i, flags, width, l)); 3959 break; 3960 } 3961 case DateTime.AM_PM: { // 'p' (am or pm) 3962 // Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper 3963 String[] ampm = { "AM", "PM" }; 3964 if (l != null && l != Locale.US) { 3965 DateFormatSymbols dfs = DateFormatSymbols.getInstance(l); 3966 ampm = dfs.getAmPmStrings(); 3967 } 3968 String s = ampm[t.get(Calendar.AM_PM)]; 3969 sb.append(s.toLowerCase(l != null ? l : Locale.US)); 3970 break; 3971 } 3972 case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?) 3973 long i = t.getTimeInMillis() / 1000; 3974 Flags flags = Flags.NONE; 3975 sb.append(localizedMagnitude(null, i, flags, width, l)); 3976 break; 3977 } 3978 case DateTime.SECOND: { // 'S' (00 - 60 - leap second) 3979 int i = t.get(Calendar.SECOND); 3980 Flags flags = Flags.ZERO_PAD; 3981 sb.append(localizedMagnitude(null, i, flags, 2, l)); 3982 break; 3983 } 3984 case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus? 3985 int i = t.get(Calendar.ZONE_OFFSET) + t.get(Calendar.DST_OFFSET); 3986 boolean neg = i < 0; 3987 sb.append(neg ? '-' : '+'); 3988 if (neg) 3989 i = -i; 3990 int min = i / 60000; 3991 // combine minute and hour into a single integer 3992 int offset = (min / 60) * 100 + (min % 60); 3993 Flags flags = Flags.ZERO_PAD; 3994 3995 sb.append(localizedMagnitude(null, offset, flags, 4, l)); 3996 break; 3997 } 3998 case DateTime.ZONE: { // 'Z' (symbol) 3999 TimeZone tz = t.getTimeZone(); 4000 sb.append(tz.getDisplayName((t.get(Calendar.DST_OFFSET) != 0), 4001 TimeZone.SHORT, 4002 (l == null) ? Locale.US : l)); 4003 break; 4004 } 4005 4006 // Date 4007 case DateTime.NAME_OF_DAY_ABBREV: // 'a' 4008 case DateTime.NAME_OF_DAY: { // 'A' 4009 int i = t.get(Calendar.DAY_OF_WEEK); 4010 Locale lt = ((l == null) ? Locale.US : l); 4011 DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt); 4012 if (c == DateTime.NAME_OF_DAY) 4013 sb.append(dfs.getWeekdays()[i]); 4014 else 4015 sb.append(dfs.getShortWeekdays()[i]); 4016 break; 4017 } 4018 case DateTime.NAME_OF_MONTH_ABBREV: // 'b' 4019 case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b 4020 case DateTime.NAME_OF_MONTH: { // 'B' 4021 int i = t.get(Calendar.MONTH); 4022 Locale lt = ((l == null) ? Locale.US : l); 4023 DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt); 4024 if (c == DateTime.NAME_OF_MONTH) 4025 sb.append(dfs.getMonths()[i]); 4026 else 4027 sb.append(dfs.getShortMonths()[i]); 4028 break; 4029 } 4030 case DateTime.CENTURY: // 'C' (00 - 99) 4031 case DateTime.YEAR_2: // 'y' (00 - 99) 4032 case DateTime.YEAR_4: { // 'Y' (0000 - 9999) 4033 int i = t.get(Calendar.YEAR); 4034 int size = 2; 4035 switch (c) { 4036 case DateTime.CENTURY: 4037 i /= 100; 4038 break; 4039 case DateTime.YEAR_2: 4040 i %= 100; 4041 break; 4042 case DateTime.YEAR_4: 4043 size = 4; 4044 break; 4045 } 4046 Flags flags = Flags.ZERO_PAD; 4047 sb.append(localizedMagnitude(null, i, flags, size, l)); 4048 break; 4049 } 4050 case DateTime.DAY_OF_MONTH_0: // 'd' (01 - 31) 4051 case DateTime.DAY_OF_MONTH: { // 'e' (1 - 31) -- like d 4052 int i = t.get(Calendar.DATE); 4053 Flags flags = (c == DateTime.DAY_OF_MONTH_0 4054 ? Flags.ZERO_PAD 4055 : Flags.NONE); 4056 sb.append(localizedMagnitude(null, i, flags, 2, l)); 4057 break; 4058 } 4059 case DateTime.DAY_OF_YEAR: { // 'j' (001 - 366) 4060 int i = t.get(Calendar.DAY_OF_YEAR); 4061 Flags flags = Flags.ZERO_PAD; 4062 sb.append(localizedMagnitude(null, i, flags, 3, l)); 4063 break; 4064 } 4065 case DateTime.MONTH: { // 'm' (01 - 12) 4066 int i = t.get(Calendar.MONTH) + 1; 4067 Flags flags = Flags.ZERO_PAD; 4068 sb.append(localizedMagnitude(null, i, flags, 2, l)); 4069 break; 4070 } 4071 4072 // Composites 4073 case DateTime.TIME: // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS) 4074 case DateTime.TIME_24_HOUR: { // 'R' (hh:mm same as %H:%M) 4075 char sep = ':'; 4076 print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep); 4077 print(sb, t, DateTime.MINUTE, l); 4078 if (c == DateTime.TIME) { 4079 sb.append(sep); 4080 print(sb, t, DateTime.SECOND, l); 4081 } 4082 break; 4083 } 4084 case DateTime.TIME_12_HOUR: { // 'r' (hh:mm:ss [AP]M) 4085 char sep = ':'; 4086 print(sb, t, DateTime.HOUR_0, l).append(sep); 4087 print(sb, t, DateTime.MINUTE, l).append(sep); 4088 print(sb, t, DateTime.SECOND, l).append(' '); 4089 // this may be in wrong place for some locales 4090 StringBuilder tsb = new StringBuilder(); 4091 print(tsb, t, DateTime.AM_PM, l); 4092 sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US)); 4093 break; 4094 } 4095 case DateTime.DATE_TIME: { // 'c' (Sat Nov 04 12:02:33 EST 1999) 4096 char sep = ' '; 4097 print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep); 4098 print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep); 4099 print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep); 4100 print(sb, t, DateTime.TIME, l).append(sep); 4101 print(sb, t, DateTime.ZONE, l).append(sep); 4102 print(sb, t, DateTime.YEAR_4, l); 4103 break; 4104 } 4105 case DateTime.DATE: { // 'D' (mm/dd/yy) 4106 char sep = '/'; 4107 print(sb, t, DateTime.MONTH, l).append(sep); 4108 print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep); 4109 print(sb, t, DateTime.YEAR_2, l); 4110 break; 4111 } 4112 case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d) 4113 char sep = '-'; 4114 print(sb, t, DateTime.YEAR_4, l).append(sep); 4115 print(sb, t, DateTime.MONTH, l).append(sep); 4116 print(sb, t, DateTime.DAY_OF_MONTH_0, l); 4117 break; 4118 } 4119 default: 4120 assert false; 4121 } 4122 return sb; 4123 } 4124 4125 // -- Methods to support throwing exceptions -- 4126 4127 private void failMismatch(Flags f, char c) { 4128 String fs = f.toString(); 4129 throw new FormatFlagsConversionMismatchException(fs, c); 4130 } 4131 4132 private void failConversion(char c, Object arg) { 4133 throw new IllegalFormatConversionException(c, arg.getClass()); 4134 } 4135 4136 private char getZero(Locale l) { 4137 if ((l != null) && !l.equals(locale())) { 4138 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); 4139 return dfs.getZeroDigit(); 4140 } 4141 return zero; 4142 } 4143 4144 private StringBuilder 4145 localizedMagnitude(StringBuilder sb, long value, Flags f, 4146 int width, Locale l) 4147 { 4148 char[] va = Long.toString(value, 10).toCharArray(); 4149 return localizedMagnitude(sb, va, f, width, l); 4150 } 4151 4152 private StringBuilder 4153 localizedMagnitude(StringBuilder sb, char[] value, Flags f, 4154 int width, Locale l) 4155 { 4156 if (sb == null) 4157 sb = new StringBuilder(); 4158 int begin = sb.length(); 4159 4160 char zero = getZero(l); 4161 4162 // determine localized grouping separator and size 4163 char grpSep = '\0'; 4164 int grpSize = -1; 4165 char decSep = '\0'; 4166 4167 int len = value.length; 4168 int dot = len; 4169 for (int j = 0; j < len; j++) { 4170 if (value[j] == '.') { 4171 dot = j; 4172 break; 4173 } 4174 } 4175 4176 if (dot < len) { 4177 if (l == null || l.equals(Locale.US)) { 4178 decSep = '.'; 4179 } else { 4180 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); 4181 decSep = dfs.getDecimalSeparator(); 4182 } 4183 } 4184 4185 if (f.contains(Flags.GROUP)) { 4186 if (l == null || l.equals(Locale.US)) { 4187 grpSep = ','; 4188 grpSize = 3; 4189 } else { 4190 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); 4191 grpSep = dfs.getGroupingSeparator(); 4192 DecimalFormat df = (DecimalFormat) NumberFormat.getIntegerInstance(l); 4193 grpSize = df.getGroupingSize(); 4194 } 4195 } 4196 4197 // localize the digits inserting group separators as necessary 4198 for (int j = 0; j < len; j++) { 4199 if (j == dot) { 4200 sb.append(decSep); 4201 // no more group separators after the decimal separator 4202 grpSep = '\0'; 4203 continue; 4204 } 4205 4206 char c = value[j]; 4207 sb.append((char) ((c - '0') + zero)); 4208 if (grpSep != '\0' && j != dot - 1 && ((dot - j) % grpSize == 1)) 4209 sb.append(grpSep); 4210 } 4211 4212 // apply zero padding 4213 len = sb.length(); 4214 if (width != -1 && f.contains(Flags.ZERO_PAD)) 4215 for (int k = 0; k < width - len; k++) 4216 sb.insert(begin, zero); 4217 4218 return sb; 4219 } 4220 } 4221 4222 private static class Flags { 4223 private int flags; 4224 4225 static final Flags NONE = new Flags(0); // '' 4226 4227 // duplicate declarations from Formattable.java 4228 static final Flags LEFT_JUSTIFY = new Flags(1<<0); // '-' 4229 static final Flags UPPERCASE = new Flags(1<<1); // '^' 4230 static final Flags ALTERNATE = new Flags(1<<2); // '#' 4231 4232 // numerics 4233 static final Flags PLUS = new Flags(1<<3); // '+' 4234 static final Flags LEADING_SPACE = new Flags(1<<4); // ' ' 4235 static final Flags ZERO_PAD = new Flags(1<<5); // '0' 4236 static final Flags GROUP = new Flags(1<<6); // ',' 4237 static final Flags PARENTHESES = new Flags(1<<7); // '(' 4238 4239 // indexing 4240 static final Flags PREVIOUS = new Flags(1<<8); // '<' 4241 4242 private Flags(int f) { 4243 flags = f; 4244 } 4245 4246 public int valueOf() { 4247 return flags; 4248 } 4249 4250 public boolean contains(Flags f) { 4251 return (flags & f.valueOf()) == f.valueOf(); 4252 } 4253 4254 public Flags dup() { 4255 return new Flags(flags); 4256 } 4257 4258 private Flags add(Flags f) { 4259 flags |= f.valueOf(); 4260 return this; 4261 } 4262 4263 public Flags remove(Flags f) { 4264 flags &= ~f.valueOf(); 4265 return this; 4266 } 4267 4268 public static Flags parse(String s) { 4269 char[] ca = s.toCharArray(); 4270 Flags f = new Flags(0); 4271 for (int i = 0; i < ca.length; i++) { 4272 Flags v = parse(ca[i]); 4273 if (f.contains(v)) 4274 throw new DuplicateFormatFlagsException(v.toString()); 4275 f.add(v); 4276 } 4277 return f; 4278 } 4279 4280 // parse those flags which may be provided by users 4281 private static Flags parse(char c) { 4282 switch (c) { 4283 case '-': return LEFT_JUSTIFY; 4284 case '#': return ALTERNATE; 4285 case '+': return PLUS; 4286 case ' ': return LEADING_SPACE; 4287 case '0': return ZERO_PAD; 4288 case ',': return GROUP; 4289 case '(': return PARENTHESES; 4290 case '<': return PREVIOUS; 4291 default: 4292 throw new UnknownFormatFlagsException(String.valueOf(c)); 4293 } 4294 } 4295 4296 // Returns a string representation of the current {@code Flags}. 4297 public static String toString(Flags f) { 4298 return f.toString(); 4299 } 4300 4301 public String toString() { 4302 StringBuilder sb = new StringBuilder(); 4303 if (contains(LEFT_JUSTIFY)) sb.append('-'); 4304 if (contains(UPPERCASE)) sb.append('^'); 4305 if (contains(ALTERNATE)) sb.append('#'); 4306 if (contains(PLUS)) sb.append('+'); 4307 if (contains(LEADING_SPACE)) sb.append(' '); 4308 if (contains(ZERO_PAD)) sb.append('0'); 4309 if (contains(GROUP)) sb.append(','); 4310 if (contains(PARENTHESES)) sb.append('('); 4311 if (contains(PREVIOUS)) sb.append('<'); 4312 return sb.toString(); 4313 } 4314 } 4315 4316 private static class Conversion { 4317 // Byte, Short, Integer, Long, BigInteger 4318 // (and associated primitives due to autoboxing) 4319 static final char DECIMAL_INTEGER = 'd'; 4320 static final char OCTAL_INTEGER = 'o'; 4321 static final char HEXADECIMAL_INTEGER = 'x'; 4322 static final char HEXADECIMAL_INTEGER_UPPER = 'X'; 4323 4324 // Float, Double, BigDecimal 4325 // (and associated primitives due to autoboxing) 4326 static final char SCIENTIFIC = 'e'; 4327 static final char SCIENTIFIC_UPPER = 'E'; 4328 static final char GENERAL = 'g'; 4329 static final char GENERAL_UPPER = 'G'; 4330 static final char DECIMAL_FLOAT = 'f'; 4331 static final char HEXADECIMAL_FLOAT = 'a'; 4332 static final char HEXADECIMAL_FLOAT_UPPER = 'A'; 4333 4334 // Character, Byte, Short, Integer 4335 // (and associated primitives due to autoboxing) 4336 static final char CHARACTER = 'c'; 4337 static final char CHARACTER_UPPER = 'C'; 4338 4339 // java.util.Date, java.util.Calendar, long 4340 static final char DATE_TIME = 't'; 4341 static final char DATE_TIME_UPPER = 'T'; 4342 4343 // if (arg.TYPE != boolean) return boolean 4344 // if (arg != null) return true; else return false; 4345 static final char BOOLEAN = 'b'; 4346 static final char BOOLEAN_UPPER = 'B'; 4347 // if (arg instanceof Formattable) arg.formatTo() 4348 // else arg.toString(); 4349 static final char STRING = 's'; 4350 static final char STRING_UPPER = 'S'; 4351 // arg.hashCode() 4352 static final char HASHCODE = 'h'; 4353 static final char HASHCODE_UPPER = 'H'; 4354 4355 static final char LINE_SEPARATOR = 'n'; 4356 static final char PERCENT_SIGN = '%'; 4357 4358 static boolean isValid(char c) { 4359 return (isGeneral(c) || isInteger(c) || isFloat(c) || isText(c) 4360 || c == 't' || isCharacter(c)); 4361 } 4362 4363 // Returns true iff the Conversion is applicable to all objects. 4364 static boolean isGeneral(char c) { 4365 switch (c) { 4366 case BOOLEAN: 4367 case BOOLEAN_UPPER: 4368 case STRING: 4369 case STRING_UPPER: 4370 case HASHCODE: 4371 case HASHCODE_UPPER: 4372 return true; 4373 default: 4374 return false; 4375 } 4376 } 4377 4378 // Returns true iff the Conversion is applicable to character. 4379 static boolean isCharacter(char c) { 4380 switch (c) { 4381 case CHARACTER: 4382 case CHARACTER_UPPER: 4383 return true; 4384 default: 4385 return false; 4386 } 4387 } 4388 4389 // Returns true iff the Conversion is an integer type. 4390 static boolean isInteger(char c) { 4391 switch (c) { 4392 case DECIMAL_INTEGER: 4393 case OCTAL_INTEGER: 4394 case HEXADECIMAL_INTEGER: 4395 case HEXADECIMAL_INTEGER_UPPER: 4396 return true; 4397 default: 4398 return false; 4399 } 4400 } 4401 4402 // Returns true iff the Conversion is a floating-point type. 4403 static boolean isFloat(char c) { 4404 switch (c) { 4405 case SCIENTIFIC: 4406 case SCIENTIFIC_UPPER: 4407 case GENERAL: 4408 case GENERAL_UPPER: 4409 case DECIMAL_FLOAT: 4410 case HEXADECIMAL_FLOAT: 4411 case HEXADECIMAL_FLOAT_UPPER: 4412 return true; 4413 default: 4414 return false; 4415 } 4416 } 4417 4418 // Returns true iff the Conversion does not require an argument 4419 static boolean isText(char c) { 4420 switch (c) { 4421 case LINE_SEPARATOR: 4422 case PERCENT_SIGN: 4423 return true; 4424 default: 4425 return false; 4426 } 4427 } 4428 } 4429 4430 private static class DateTime { 4431 static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23) 4432 static final char HOUR_0 = 'I'; // (01 - 12) 4433 static final char HOUR_OF_DAY = 'k'; // (0 - 23) -- like H 4434 static final char HOUR = 'l'; // (1 - 12) -- like I 4435 static final char MINUTE = 'M'; // (00 - 59) 4436 static final char NANOSECOND = 'N'; // (000000000 - 999999999) 4437 static final char MILLISECOND = 'L'; // jdk, not in gnu (000 - 999) 4438 static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?) 4439 static final char AM_PM = 'p'; // (am or pm) 4440 static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?) 4441 static final char SECOND = 'S'; // (00 - 60 - leap second) 4442 static final char TIME = 'T'; // (24 hour hh:mm:ss) 4443 static final char ZONE_NUMERIC = 'z'; // (-1200 - +1200) - ls minus? 4444 static final char ZONE = 'Z'; // (symbol) 4445 4446 // Date 4447 static final char NAME_OF_DAY_ABBREV = 'a'; // 'a' 4448 static final char NAME_OF_DAY = 'A'; // 'A' 4449 static final char NAME_OF_MONTH_ABBREV = 'b'; // 'b' 4450 static final char NAME_OF_MONTH = 'B'; // 'B' 4451 static final char CENTURY = 'C'; // (00 - 99) 4452 static final char DAY_OF_MONTH_0 = 'd'; // (01 - 31) 4453 static final char DAY_OF_MONTH = 'e'; // (1 - 31) -- like d 4454// * static final char ISO_WEEK_OF_YEAR_2 = 'g'; // cross %y %V 4455// * static final char ISO_WEEK_OF_YEAR_4 = 'G'; // cross %Y %V 4456 static final char NAME_OF_MONTH_ABBREV_X = 'h'; // -- same b 4457 static final char DAY_OF_YEAR = 'j'; // (001 - 366) 4458 static final char MONTH = 'm'; // (01 - 12) 4459// * static final char DAY_OF_WEEK_1 = 'u'; // (1 - 7) Monday 4460// * static final char WEEK_OF_YEAR_SUNDAY = 'U'; // (0 - 53) Sunday+ 4461// * static final char WEEK_OF_YEAR_MONDAY_01 = 'V'; // (01 - 53) Monday+ 4462// * static final char DAY_OF_WEEK_0 = 'w'; // (0 - 6) Sunday 4463// * static final char WEEK_OF_YEAR_MONDAY = 'W'; // (00 - 53) Monday 4464 static final char YEAR_2 = 'y'; // (00 - 99) 4465 static final char YEAR_4 = 'Y'; // (0000 - 9999) 4466 4467 // Composites 4468 static final char TIME_12_HOUR = 'r'; // (hh:mm:ss [AP]M) 4469 static final char TIME_24_HOUR = 'R'; // (hh:mm same as %H:%M) 4470// * static final char LOCALE_TIME = 'X'; // (%H:%M:%S) - parse format? 4471 static final char DATE_TIME = 'c'; 4472 // (Sat Nov 04 12:02:33 EST 1999) 4473 static final char DATE = 'D'; // (mm/dd/yy) 4474 static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d) 4475// * static final char LOCALE_DATE = 'x'; // (mm/dd/yy) 4476 4477 static boolean isValid(char c) { 4478 switch (c) { 4479 case HOUR_OF_DAY_0: 4480 case HOUR_0: 4481 case HOUR_OF_DAY: 4482 case HOUR: 4483 case MINUTE: 4484 case NANOSECOND: 4485 case MILLISECOND: 4486 case MILLISECOND_SINCE_EPOCH: 4487 case AM_PM: 4488 case SECONDS_SINCE_EPOCH: 4489 case SECOND: 4490 case TIME: 4491 case ZONE_NUMERIC: 4492 case ZONE: 4493 4494 // Date 4495 case NAME_OF_DAY_ABBREV: 4496 case NAME_OF_DAY: 4497 case NAME_OF_MONTH_ABBREV: 4498 case NAME_OF_MONTH: 4499 case CENTURY: 4500 case DAY_OF_MONTH_0: 4501 case DAY_OF_MONTH: 4502// * case ISO_WEEK_OF_YEAR_2: 4503// * case ISO_WEEK_OF_YEAR_4: 4504 case NAME_OF_MONTH_ABBREV_X: 4505 case DAY_OF_YEAR: 4506 case MONTH: 4507// * case DAY_OF_WEEK_1: 4508// * case WEEK_OF_YEAR_SUNDAY: 4509// * case WEEK_OF_YEAR_MONDAY_01: 4510// * case DAY_OF_WEEK_0: 4511// * case WEEK_OF_YEAR_MONDAY: 4512 case YEAR_2: 4513 case YEAR_4: 4514 4515 // Composites 4516 case TIME_12_HOUR: 4517 case TIME_24_HOUR: 4518// * case LOCALE_TIME: 4519 case DATE_TIME: 4520 case DATE: 4521 case ISO_STANDARD_DATE: 4522// * case LOCALE_DATE: 4523 return true; 4524 default: 4525 return false; 4526 } 4527 } 4528 } 4529} 4530