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