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