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