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