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