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