1 /*
   2  * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.util.Objects;
  29 import java.util.Formatter;
  30 import java.util.Locale;
  31 import java.nio.charset.Charset;
  32 import java.nio.charset.IllegalCharsetNameException;
  33 
  34 /**
  35  * Prints formatted representations of objects to a text-output stream.  This
  36  * class implements all of the <tt>print</tt> methods found in {@link
  37  * PrintStream}.  It does not contain methods for writing raw bytes, for which
  38  * a program should use unencoded byte streams.
  39  *
  40  * <p> Unlike the {@link PrintStream} class, if automatic flushing is enabled
  41  * it will be done only when one of the <tt>println</tt>, <tt>printf</tt>, or
  42  * <tt>format</tt> methods is invoked, rather than whenever a newline character
  43  * happens to be output.  These methods use the platform's own notion of line
  44  * separator rather than the newline character.
  45  *
  46  * <p> Methods in this class never throw I/O exceptions, although some of its
  47  * constructors may.  The client may inquire as to whether any errors have
  48  * occurred by invoking {@link #checkError checkError()}.
  49  *
  50  * @author      Frank Yellin
  51  * @author      Mark Reinhold
  52  * @since       JDK1.1
  53  */
  54 
  55 public class PrintWriter extends Writer {
  56 
  57     /**
  58      * The underlying character-output stream of this
  59      * <code>PrintWriter</code>.
  60      *
  61      * @since 1.2
  62      */
  63     protected Writer out;
  64 
  65     private final boolean autoFlush;
  66     private boolean trouble = false;
  67     private Formatter formatter;
  68     private PrintStream psOut = null;
  69 
  70     /**
  71      * Line separator string.  This is the value of the line.separator
  72      * property at the moment that the stream was created.
  73      */
  74     private final String lineSeparator;
  75 
  76     /**
  77      * Returns a charset object for the given charset name.
  78      * @throws NullPointerException          is csn is null
  79      * @throws UnsupportedEncodingException  if the charset is not supported
  80      */
  81     private static Charset toCharset(String csn)
  82             throws UnsupportedEncodingException {
  83         Objects.nonNull(csn, "charsetName");
  84         try {
  85             return Charset.forName(csn);
  86         } catch (IllegalCharsetNameException unused) {
  87             /* swallow this exception since UnsupportedEncodingException
  88              * will be thrown */
  89         }
  90         throw new UnsupportedEncodingException(csn);
  91     }
  92 
  93     /**
  94      * Creates a new PrintWriter, without automatic line flushing.
  95      *
  96      * @param  out        A character-output stream
  97      */
  98     public PrintWriter (Writer out) {
  99         this(out, false);
 100     }
 101 
 102     /**
 103      * Creates a new PrintWriter.
 104      *
 105      * @param  out        A character-output stream
 106      * @param  autoFlush  A boolean; if true, the <tt>println</tt>,
 107      *                    <tt>printf</tt>, or <tt>format</tt> methods will
 108      *                    flush the output buffer
 109      */
 110     public PrintWriter(Writer out,
 111                        boolean autoFlush) {
 112         super(out);
 113         this.out = out;
 114         this.autoFlush = autoFlush;
 115         lineSeparator = java.security.AccessController.doPrivileged(
 116             new sun.security.action.GetPropertyAction("line.separator"));
 117     }
 118 
 119     /**
 120      * Creates a new PrintWriter, without automatic line flushing, from an
 121      * existing OutputStream.  This convenience constructor creates the
 122      * necessary intermediate OutputStreamWriter, which will convert characters
 123      * into bytes using the default character encoding.
 124      *
 125      * @param  out        An output stream
 126      *
 127      * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 128      */
 129     public PrintWriter(OutputStream out) {
 130         this(out, false);
 131     }
 132 
 133     /**
 134      * Creates a new PrintWriter from an existing OutputStream.  This
 135      * convenience constructor creates the necessary intermediate
 136      * OutputStreamWriter, which will convert characters into bytes using the
 137      * default character encoding.
 138      *
 139      * @param  out        An output stream
 140      * @param  autoFlush  A boolean; if true, the <tt>println</tt>,
 141      *                    <tt>printf</tt>, or <tt>format</tt> methods will
 142      *                    flush the output buffer
 143      *
 144      * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 145      */
 146     public PrintWriter(OutputStream out, boolean autoFlush) {
 147         this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
 148 
 149         // save print stream for error propagation
 150         if (out instanceof java.io.PrintStream) {
 151             psOut = (PrintStream) out;
 152         }
 153     }
 154 
 155     /**
 156      * Creates a new PrintWriter, without automatic line flushing, with the
 157      * specified file name.  This convenience constructor creates the necessary
 158      * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
 159      * which will encode characters using the {@linkplain
 160      * java.nio.charset.Charset#defaultCharset() default charset} for this
 161      * instance of the Java virtual machine.
 162      *
 163      * @param  fileName
 164      *         The name of the file to use as the destination of this writer.
 165      *         If the file exists then it will be truncated to zero size;
 166      *         otherwise, a new file will be created.  The output will be
 167      *         written to the file and is buffered.
 168      *
 169      * @throws  FileNotFoundException
 170      *          If the given string does not denote an existing, writable
 171      *          regular file and a new regular file of that name cannot be
 172      *          created, or if some other error occurs while opening or
 173      *          creating the file
 174      *
 175      * @throws  SecurityException
 176      *          If a security manager is present and {@link
 177      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 178      *          access to the file
 179      *
 180      * @since  1.5
 181      */
 182     public PrintWriter(String fileName) throws FileNotFoundException {
 183         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
 184              false);
 185     }
 186 
 187     /* Private constructor*/
 188     private PrintWriter(Charset charset, File file) throws FileNotFoundException {
 189         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),
 190              false);
 191     }
 192 
 193     /**
 194      * Creates a new PrintWriter, without automatic line flushing, with the
 195      * specified file name and charset.  This convenience constructor creates
 196      * the necessary intermediate {@link java.io.OutputStreamWriter
 197      * OutputStreamWriter}, which will encode characters using the provided
 198      * charset.
 199      *
 200      * @param  fileName
 201      *         The name of the file to use as the destination of this writer.
 202      *         If the file exists then it will be truncated to zero size;
 203      *         otherwise, a new file will be created.  The output will be
 204      *         written to the file and is buffered.
 205      *
 206      * @param  csn
 207      *         The name of a supported {@linkplain java.nio.charset.Charset
 208      *         charset}
 209      *
 210      * @throws  FileNotFoundException
 211      *          If the given string does not denote an existing, writable
 212      *          regular file and a new regular file of that name cannot be
 213      *          created, or if some other error occurs while opening or
 214      *          creating the file
 215      *
 216      * @throws  SecurityException
 217      *          If a security manager is present and {@link
 218      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 219      *          access to the file
 220      *
 221      * @throws  UnsupportedEncodingException
 222      *          If the named charset is not supported
 223      *
 224      * @since  1.5
 225      */
 226     public PrintWriter(String fileName, String csn)
 227         throws FileNotFoundException, UnsupportedEncodingException
 228     {
 229         this(toCharset(csn), new File(fileName));
 230     }
 231 
 232     /**
 233      * Creates a new PrintWriter, without automatic line flushing, with the
 234      * specified file.  This convenience constructor creates the necessary
 235      * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
 236      * which will encode characters using the {@linkplain
 237      * java.nio.charset.Charset#defaultCharset() default charset} for this
 238      * instance of the Java virtual machine.
 239      *
 240      * @param  file
 241      *         The file to use as the destination of this writer.  If the file
 242      *         exists then it will be truncated to zero size; otherwise, a new
 243      *         file will be created.  The output will be written to the file
 244      *         and is buffered.
 245      *
 246      * @throws  FileNotFoundException
 247      *          If the given file object does not denote an existing, writable
 248      *          regular file and a new regular file of that name cannot be
 249      *          created, or if some other error occurs while opening or
 250      *          creating the file
 251      *
 252      * @throws  SecurityException
 253      *          If a security manager is present and {@link
 254      *          SecurityManager#checkWrite checkWrite(file.getPath())}
 255      *          denies write access to the file
 256      *
 257      * @since  1.5
 258      */
 259     public PrintWriter(File file) throws FileNotFoundException {
 260         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
 261              false);
 262     }
 263 
 264     /**
 265      * Creates a new PrintWriter, without automatic line flushing, with the
 266      * specified file and charset.  This convenience constructor creates the
 267      * necessary intermediate {@link java.io.OutputStreamWriter
 268      * OutputStreamWriter}, which will encode characters using the provided
 269      * charset.
 270      *
 271      * @param  file
 272      *         The file to use as the destination of this writer.  If the file
 273      *         exists then it will be truncated to zero size; otherwise, a new
 274      *         file will be created.  The output will be written to the file
 275      *         and is buffered.
 276      *
 277      * @param  csn
 278      *         The name of a supported {@linkplain java.nio.charset.Charset
 279      *         charset}
 280      *
 281      * @throws  FileNotFoundException
 282      *          If the given file object does not denote an existing, writable
 283      *          regular file and a new regular file of that name cannot be
 284      *          created, or if some other error occurs while opening or
 285      *          creating the file
 286      *
 287      * @throws  SecurityException
 288      *          If a security manager is present and {@link
 289      *          SecurityManager#checkWrite checkWrite(file.getPath())}
 290      *          denies write access to the file
 291      *
 292      * @throws  UnsupportedEncodingException
 293      *          If the named charset is not supported
 294      *
 295      * @since  1.5
 296      */
 297     public PrintWriter(File file, String csn)
 298         throws FileNotFoundException, UnsupportedEncodingException
 299     {
 300         this(toCharset(csn), file);
 301     }
 302 
 303     /** Checks to make sure that the stream has not been closed */
 304     private void ensureOpen() throws IOException {
 305         if (out == null)
 306             throw new IOException("Stream closed");
 307     }
 308 
 309     /**
 310      * Flushes the stream.
 311      * @see #checkError()
 312      */
 313     public void flush() {
 314         try {
 315             synchronized (lock) {
 316                 ensureOpen();
 317                 out.flush();
 318             }
 319         }
 320         catch (IOException x) {
 321             trouble = true;
 322         }
 323     }
 324 
 325     /**
 326      * Closes the stream and releases any system resources associated
 327      * with it. Closing a previously closed stream has no effect.
 328      *
 329      * @see #checkError()
 330      */
 331     public void close() {
 332         try {
 333             synchronized (lock) {
 334                 if (out == null)
 335                     return;
 336                 out.close();
 337                 out = null;
 338             }
 339         }
 340         catch (IOException x) {
 341             trouble = true;
 342         }
 343     }
 344 
 345     /**
 346      * Flushes the stream if it's not closed and checks its error state.
 347      *
 348      * @return <code>true</code> if the print stream has encountered an error,
 349      *          either on the underlying output stream or during a format
 350      *          conversion.
 351      */
 352     public boolean checkError() {
 353         if (out != null) {
 354             flush();
 355         }
 356         if (out instanceof java.io.PrintWriter) {
 357             PrintWriter pw = (PrintWriter) out;
 358             return pw.checkError();
 359         } else if (psOut != null) {
 360             return psOut.checkError();
 361         }
 362         return trouble;
 363     }
 364 
 365     /**
 366      * Indicates that an error has occurred.
 367      *
 368      * <p> This method will cause subsequent invocations of {@link
 369      * #checkError()} to return <tt>true</tt> until {@link
 370      * #clearError()} is invoked.
 371      */
 372     protected void setError() {
 373         trouble = true;
 374     }
 375 
 376     /**
 377      * Clears the error state of this stream.
 378      *
 379      * <p> This method will cause subsequent invocations of {@link
 380      * #checkError()} to return <tt>false</tt> until another write
 381      * operation fails and invokes {@link #setError()}.
 382      *
 383      * @since 1.6
 384      */
 385     protected void clearError() {
 386         trouble = false;
 387     }
 388 
 389     /*
 390      * Exception-catching, synchronized output operations,
 391      * which also implement the write() methods of Writer
 392      */
 393 
 394     /**
 395      * Writes a single character.
 396      * @param c int specifying a character to be written.
 397      */
 398     public void write(int c) {
 399         try {
 400             synchronized (lock) {
 401                 ensureOpen();
 402                 out.write(c);
 403             }
 404         }
 405         catch (InterruptedIOException x) {
 406             Thread.currentThread().interrupt();
 407         }
 408         catch (IOException x) {
 409             trouble = true;
 410         }
 411     }
 412 
 413     /**
 414      * Writes A Portion of an array of characters.
 415      * @param buf Array of characters
 416      * @param off Offset from which to start writing characters
 417      * @param len Number of characters to write
 418      */
 419     public void write(char buf[], int off, int len) {
 420         try {
 421             synchronized (lock) {
 422                 ensureOpen();
 423                 out.write(buf, off, len);
 424             }
 425         }
 426         catch (InterruptedIOException x) {
 427             Thread.currentThread().interrupt();
 428         }
 429         catch (IOException x) {
 430             trouble = true;
 431         }
 432     }
 433 
 434     /**
 435      * Writes an array of characters.  This method cannot be inherited from the
 436      * Writer class because it must suppress I/O exceptions.
 437      * @param buf Array of characters to be written
 438      */
 439     public void write(char buf[]) {
 440         write(buf, 0, buf.length);
 441     }
 442 
 443     /**
 444      * Writes a portion of a string.
 445      * @param s A String
 446      * @param off Offset from which to start writing characters
 447      * @param len Number of characters to write
 448      */
 449     public void write(String s, int off, int len) {
 450         try {
 451             synchronized (lock) {
 452                 ensureOpen();
 453                 out.write(s, off, len);
 454             }
 455         }
 456         catch (InterruptedIOException x) {
 457             Thread.currentThread().interrupt();
 458         }
 459         catch (IOException x) {
 460             trouble = true;
 461         }
 462     }
 463 
 464     /**
 465      * Writes a string.  This method cannot be inherited from the Writer class
 466      * because it must suppress I/O exceptions.
 467      * @param s String to be written
 468      */
 469     public void write(String s) {
 470         write(s, 0, s.length());
 471     }
 472 
 473     private void newLine() {
 474         try {
 475             synchronized (lock) {
 476                 ensureOpen();
 477                 out.write(lineSeparator);
 478                 if (autoFlush)
 479                     out.flush();
 480             }
 481         }
 482         catch (InterruptedIOException x) {
 483             Thread.currentThread().interrupt();
 484         }
 485         catch (IOException x) {
 486             trouble = true;
 487         }
 488     }
 489 
 490     /* Methods that do not terminate lines */
 491 
 492     /**
 493      * Prints a boolean value.  The string produced by <code>{@link
 494      * java.lang.String#valueOf(boolean)}</code> is translated into bytes
 495      * according to the platform's default character encoding, and these bytes
 496      * are written in exactly the manner of the <code>{@link
 497      * #write(int)}</code> method.
 498      *
 499      * @param      b   The <code>boolean</code> to be printed
 500      */
 501     public void print(boolean b) {
 502         write(b ? "true" : "false");
 503     }
 504 
 505     /**
 506      * Prints a character.  The character is translated into one or more bytes
 507      * according to the platform's default character encoding, and these bytes
 508      * are written in exactly the manner of the <code>{@link
 509      * #write(int)}</code> method.
 510      *
 511      * @param      c   The <code>char</code> to be printed
 512      */
 513     public void print(char c) {
 514         write(c);
 515     }
 516 
 517     /**
 518      * Prints an integer.  The string produced by <code>{@link
 519      * java.lang.String#valueOf(int)}</code> is translated into bytes according
 520      * to the platform's default character encoding, and these bytes are
 521      * written in exactly the manner of the <code>{@link #write(int)}</code>
 522      * method.
 523      *
 524      * @param      i   The <code>int</code> to be printed
 525      * @see        java.lang.Integer#toString(int)
 526      */
 527     public void print(int i) {
 528         write(String.valueOf(i));
 529     }
 530 
 531     /**
 532      * Prints a long integer.  The string produced by <code>{@link
 533      * java.lang.String#valueOf(long)}</code> is translated into bytes
 534      * according to the platform's default character encoding, and these bytes
 535      * are written in exactly the manner of the <code>{@link #write(int)}</code>
 536      * method.
 537      *
 538      * @param      l   The <code>long</code> to be printed
 539      * @see        java.lang.Long#toString(long)
 540      */
 541     public void print(long l) {
 542         write(String.valueOf(l));
 543     }
 544 
 545     /**
 546      * Prints a floating-point number.  The string produced by <code>{@link
 547      * java.lang.String#valueOf(float)}</code> is translated into bytes
 548      * according to the platform's default character encoding, and these bytes
 549      * are written in exactly the manner of the <code>{@link #write(int)}</code>
 550      * method.
 551      *
 552      * @param      f   The <code>float</code> to be printed
 553      * @see        java.lang.Float#toString(float)
 554      */
 555     public void print(float f) {
 556         write(String.valueOf(f));
 557     }
 558 
 559     /**
 560      * Prints a double-precision floating-point number.  The string produced by
 561      * <code>{@link java.lang.String#valueOf(double)}</code> is translated into
 562      * bytes according to the platform's default character encoding, and these
 563      * bytes are written in exactly the manner of the <code>{@link
 564      * #write(int)}</code> method.
 565      *
 566      * @param      d   The <code>double</code> to be printed
 567      * @see        java.lang.Double#toString(double)
 568      */
 569     public void print(double d) {
 570         write(String.valueOf(d));
 571     }
 572 
 573     /**
 574      * Prints an array of characters.  The characters are converted into bytes
 575      * according to the platform's default character encoding, and these bytes
 576      * are written in exactly the manner of the <code>{@link #write(int)}</code>
 577      * method.
 578      *
 579      * @param      s   The array of chars to be printed
 580      *
 581      * @throws  NullPointerException  If <code>s</code> is <code>null</code>
 582      */
 583     public void print(char s[]) {
 584         write(s);
 585     }
 586 
 587     /**
 588      * Prints a string.  If the argument is <code>null</code> then the string
 589      * <code>"null"</code> is printed.  Otherwise, the string's characters are
 590      * converted into bytes according to the platform's default character
 591      * encoding, and these bytes are written in exactly the manner of the
 592      * <code>{@link #write(int)}</code> method.
 593      *
 594      * @param      s   The <code>String</code> to be printed
 595      */
 596     public void print(String s) {
 597         if (s == null) {
 598             s = "null";
 599         }
 600         write(s);
 601     }
 602 
 603     /**
 604      * Prints an object.  The string produced by the <code>{@link
 605      * java.lang.String#valueOf(Object)}</code> method is translated into bytes
 606      * according to the platform's default character encoding, and these bytes
 607      * are written in exactly the manner of the <code>{@link #write(int)}</code>
 608      * method.
 609      *
 610      * @param      obj   The <code>Object</code> to be printed
 611      * @see        java.lang.Object#toString()
 612      */
 613     public void print(Object obj) {
 614         write(String.valueOf(obj));
 615     }
 616 
 617     /* Methods that do terminate lines */
 618 
 619     /**
 620      * Terminates the current line by writing the line separator string.  The
 621      * line separator string is defined by the system property
 622      * <code>line.separator</code>, and is not necessarily a single newline
 623      * character (<code>'\n'</code>).
 624      */
 625     public void println() {
 626         newLine();
 627     }
 628 
 629     /**
 630      * Prints a boolean value and then terminates the line.  This method behaves
 631      * as though it invokes <code>{@link #print(boolean)}</code> and then
 632      * <code>{@link #println()}</code>.
 633      *
 634      * @param x the <code>boolean</code> value to be printed
 635      */
 636     public void println(boolean x) {
 637         synchronized (lock) {
 638             print(x);
 639             println();
 640         }
 641     }
 642 
 643     /**
 644      * Prints a character and then terminates the line.  This method behaves as
 645      * though it invokes <code>{@link #print(char)}</code> and then <code>{@link
 646      * #println()}</code>.
 647      *
 648      * @param x the <code>char</code> value to be printed
 649      */
 650     public void println(char x) {
 651         synchronized (lock) {
 652             print(x);
 653             println();
 654         }
 655     }
 656 
 657     /**
 658      * Prints an integer and then terminates the line.  This method behaves as
 659      * though it invokes <code>{@link #print(int)}</code> and then <code>{@link
 660      * #println()}</code>.
 661      *
 662      * @param x the <code>int</code> value to be printed
 663      */
 664     public void println(int x) {
 665         synchronized (lock) {
 666             print(x);
 667             println();
 668         }
 669     }
 670 
 671     /**
 672      * Prints a long integer and then terminates the line.  This method behaves
 673      * as though it invokes <code>{@link #print(long)}</code> and then
 674      * <code>{@link #println()}</code>.
 675      *
 676      * @param x the <code>long</code> value to be printed
 677      */
 678     public void println(long x) {
 679         synchronized (lock) {
 680             print(x);
 681             println();
 682         }
 683     }
 684 
 685     /**
 686      * Prints a floating-point number and then terminates the line.  This method
 687      * behaves as though it invokes <code>{@link #print(float)}</code> and then
 688      * <code>{@link #println()}</code>.
 689      *
 690      * @param x the <code>float</code> value to be printed
 691      */
 692     public void println(float x) {
 693         synchronized (lock) {
 694             print(x);
 695             println();
 696         }
 697     }
 698 
 699     /**
 700      * Prints a double-precision floating-point number and then terminates the
 701      * line.  This method behaves as though it invokes <code>{@link
 702      * #print(double)}</code> and then <code>{@link #println()}</code>.
 703      *
 704      * @param x the <code>double</code> value to be printed
 705      */
 706     public void println(double x) {
 707         synchronized (lock) {
 708             print(x);
 709             println();
 710         }
 711     }
 712 
 713     /**
 714      * Prints an array of characters and then terminates the line.  This method
 715      * behaves as though it invokes <code>{@link #print(char[])}</code> and then
 716      * <code>{@link #println()}</code>.
 717      *
 718      * @param x the array of <code>char</code> values to be printed
 719      */
 720     public void println(char x[]) {
 721         synchronized (lock) {
 722             print(x);
 723             println();
 724         }
 725     }
 726 
 727     /**
 728      * Prints a String and then terminates the line.  This method behaves as
 729      * though it invokes <code>{@link #print(String)}</code> and then
 730      * <code>{@link #println()}</code>.
 731      *
 732      * @param x the <code>String</code> value to be printed
 733      */
 734     public void println(String x) {
 735         synchronized (lock) {
 736             print(x);
 737             println();
 738         }
 739     }
 740 
 741     /**
 742      * Prints an Object and then terminates the line.  This method calls
 743      * at first String.valueOf(x) to get the printed object's string value,
 744      * then behaves as
 745      * though it invokes <code>{@link #print(String)}</code> and then
 746      * <code>{@link #println()}</code>.
 747      *
 748      * @param x  The <code>Object</code> to be printed.
 749      */
 750     public void println(Object x) {
 751         String s = String.valueOf(x);
 752         synchronized (lock) {
 753             print(s);
 754             println();
 755         }
 756     }
 757 
 758     /**
 759      * A convenience method to write a formatted string to this writer using
 760      * the specified format string and arguments.  If automatic flushing is
 761      * enabled, calls to this method will flush the output buffer.
 762      *
 763      * <p> An invocation of this method of the form <tt>out.printf(format,
 764      * args)</tt> behaves in exactly the same way as the invocation
 765      *
 766      * <pre>
 767      *     out.format(format, args) </pre>
 768      *
 769      * @param  format
 770      *         A format string as described in <a
 771      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
 772      *
 773      * @param  args
 774      *         Arguments referenced by the format specifiers in the format
 775      *         string.  If there are more arguments than format specifiers, the
 776      *         extra arguments are ignored.  The number of arguments is
 777      *         variable and may be zero.  The maximum number of arguments is
 778      *         limited by the maximum dimension of a Java array as defined by
 779      *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
 780      *         Virtual Machine Specification</a>.  The behaviour on a
 781      *         <tt>null</tt> argument depends on the <a
 782      *         href="../util/Formatter.html#syntax">conversion</a>.
 783      *
 784      * @throws  IllegalFormatException
 785      *          If a format string contains an illegal syntax, a format
 786      *          specifier that is incompatible with the given arguments,
 787      *          insufficient arguments given the format string, or other
 788      *          illegal conditions.  For specification of all possible
 789      *          formatting errors, see the <a
 790      *          href="../util/Formatter.html#detail">Details</a> section of the
 791      *          formatter class specification.
 792      *
 793      * @throws  NullPointerException
 794      *          If the <tt>format</tt> is <tt>null</tt>
 795      *
 796      * @return  This writer
 797      *
 798      * @since  1.5
 799      */
 800     public PrintWriter printf(String format, Object ... args) {
 801         return format(format, args);
 802     }
 803 
 804     /**
 805      * A convenience method to write a formatted string to this writer using
 806      * the specified format string and arguments.  If automatic flushing is
 807      * enabled, calls to this method will flush the output buffer.
 808      *
 809      * <p> An invocation of this method of the form <tt>out.printf(l, format,
 810      * args)</tt> behaves in exactly the same way as the invocation
 811      *
 812      * <pre>
 813      *     out.format(l, format, args) </pre>
 814      *
 815      * @param  l
 816      *         The {@linkplain java.util.Locale locale} to apply during
 817      *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
 818      *         is applied.
 819      *
 820      * @param  format
 821      *         A format string as described in <a
 822      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
 823      *
 824      * @param  args
 825      *         Arguments referenced by the format specifiers in the format
 826      *         string.  If there are more arguments than format specifiers, the
 827      *         extra arguments are ignored.  The number of arguments is
 828      *         variable and may be zero.  The maximum number of arguments is
 829      *         limited by the maximum dimension of a Java array as defined by
 830      *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
 831      *         Virtual Machine Specification</a>.  The behaviour on a
 832      *         <tt>null</tt> argument depends on the <a
 833      *         href="../util/Formatter.html#syntax">conversion</a>.
 834      *
 835      * @throws  IllegalFormatException
 836      *          If a format string contains an illegal syntax, a format
 837      *          specifier that is incompatible with the given arguments,
 838      *          insufficient arguments given the format string, or other
 839      *          illegal conditions.  For specification of all possible
 840      *          formatting errors, see the <a
 841      *          href="../util/Formatter.html#detail">Details</a> section of the
 842      *          formatter class specification.
 843      *
 844      * @throws  NullPointerException
 845      *          If the <tt>format</tt> is <tt>null</tt>
 846      *
 847      * @return  This writer
 848      *
 849      * @since  1.5
 850      */
 851     public PrintWriter printf(Locale l, String format, Object ... args) {
 852         return format(l, format, args);
 853     }
 854 
 855     /**
 856      * Writes a formatted string to this writer using the specified format
 857      * string and arguments.  If automatic flushing is enabled, calls to this
 858      * method will flush the output buffer.
 859      *
 860      * <p> The locale always used is the one returned by {@link
 861      * java.util.Locale#getDefault() Locale.getDefault()}, regardless of any
 862      * previous invocations of other formatting methods on this object.
 863      *
 864      * @param  format
 865      *         A format string as described in <a
 866      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
 867      *
 868      * @param  args
 869      *         Arguments referenced by the format specifiers in the format
 870      *         string.  If there are more arguments than format specifiers, the
 871      *         extra arguments are ignored.  The number of arguments is
 872      *         variable and may be zero.  The maximum number of arguments is
 873      *         limited by the maximum dimension of a Java array as defined by
 874      *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
 875      *         Virtual Machine Specification</a>.  The behaviour on a
 876      *         <tt>null</tt> argument depends on the <a
 877      *         href="../util/Formatter.html#syntax">conversion</a>.
 878      *
 879      * @throws  IllegalFormatException
 880      *          If a format string contains an illegal syntax, a format
 881      *          specifier that is incompatible with the given arguments,
 882      *          insufficient arguments given the format string, or other
 883      *          illegal conditions.  For specification of all possible
 884      *          formatting errors, see the <a
 885      *          href="../util/Formatter.html#detail">Details</a> section of the
 886      *          Formatter class specification.
 887      *
 888      * @throws  NullPointerException
 889      *          If the <tt>format</tt> is <tt>null</tt>
 890      *
 891      * @return  This writer
 892      *
 893      * @since  1.5
 894      */
 895     public PrintWriter format(String format, Object ... args) {
 896         try {
 897             synchronized (lock) {
 898                 ensureOpen();
 899                 if ((formatter == null)
 900                     || (formatter.locale() != Locale.getDefault()))
 901                     formatter = new Formatter(this);
 902                 formatter.format(Locale.getDefault(), format, args);
 903                 if (autoFlush)
 904                     out.flush();
 905             }
 906         } catch (InterruptedIOException x) {
 907             Thread.currentThread().interrupt();
 908         } catch (IOException x) {
 909             trouble = true;
 910         }
 911         return this;
 912     }
 913 
 914     /**
 915      * Writes a formatted string to this writer using the specified format
 916      * string and arguments.  If automatic flushing is enabled, calls to this
 917      * method will flush the output buffer.
 918      *
 919      * @param  l
 920      *         The {@linkplain java.util.Locale locale} to apply during
 921      *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
 922      *         is applied.
 923      *
 924      * @param  format
 925      *         A format string as described in <a
 926      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
 927      *
 928      * @param  args
 929      *         Arguments referenced by the format specifiers in the format
 930      *         string.  If there are more arguments than format specifiers, the
 931      *         extra arguments are ignored.  The number of arguments is
 932      *         variable and may be zero.  The maximum number of arguments is
 933      *         limited by the maximum dimension of a Java array as defined by
 934      *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
 935      *         Virtual Machine Specification</a>.  The behaviour on a
 936      *         <tt>null</tt> argument depends on the <a
 937      *         href="../util/Formatter.html#syntax">conversion</a>.
 938      *
 939      * @throws  IllegalFormatException
 940      *          If a format string contains an illegal syntax, a format
 941      *          specifier that is incompatible with the given arguments,
 942      *          insufficient arguments given the format string, or other
 943      *          illegal conditions.  For specification of all possible
 944      *          formatting errors, see the <a
 945      *          href="../util/Formatter.html#detail">Details</a> section of the
 946      *          formatter class specification.
 947      *
 948      * @throws  NullPointerException
 949      *          If the <tt>format</tt> is <tt>null</tt>
 950      *
 951      * @return  This writer
 952      *
 953      * @since  1.5
 954      */
 955     public PrintWriter format(Locale l, String format, Object ... args) {
 956         try {
 957             synchronized (lock) {
 958                 ensureOpen();
 959                 if ((formatter == null) || (formatter.locale() != l))
 960                     formatter = new Formatter(this, l);
 961                 formatter.format(l, format, args);
 962                 if (autoFlush)
 963                     out.flush();
 964             }
 965         } catch (InterruptedIOException x) {
 966             Thread.currentThread().interrupt();
 967         } catch (IOException x) {
 968             trouble = true;
 969         }
 970         return this;
 971     }
 972 
 973     /**
 974      * Appends the specified character sequence to this writer.
 975      *
 976      * <p> An invocation of this method of the form <tt>out.append(csq)</tt>
 977      * behaves in exactly the same way as the invocation
 978      *
 979      * <pre>
 980      *     out.write(csq.toString()) </pre>
 981      *
 982      * <p> Depending on the specification of <tt>toString</tt> for the
 983      * character sequence <tt>csq</tt>, the entire sequence may not be
 984      * appended. For instance, invoking the <tt>toString</tt> method of a
 985      * character buffer will return a subsequence whose content depends upon
 986      * the buffer's position and limit.
 987      *
 988      * @param  csq
 989      *         The character sequence to append.  If <tt>csq</tt> is
 990      *         <tt>null</tt>, then the four characters <tt>"null"</tt> are
 991      *         appended to this writer.
 992      *
 993      * @return  This writer
 994      *
 995      * @since  1.5
 996      */
 997     public PrintWriter append(CharSequence csq) {
 998         if (csq == null)
 999             write("null");
1000         else
1001             write(csq.toString());
1002         return this;
1003     }
1004 
1005     /**
1006      * Appends a subsequence of the specified character sequence to this writer.
1007      *
1008      * <p> An invocation of this method of the form <tt>out.append(csq, start,
1009      * end)</tt> when <tt>csq</tt> is not <tt>null</tt>, behaves in
1010      * exactly the same way as the invocation
1011      *
1012      * <pre>
1013      *     out.write(csq.subSequence(start, end).toString()) </pre>
1014      *
1015      * @param  csq
1016      *         The character sequence from which a subsequence will be
1017      *         appended.  If <tt>csq</tt> is <tt>null</tt>, then characters
1018      *         will be appended as if <tt>csq</tt> contained the four
1019      *         characters <tt>"null"</tt>.
1020      *
1021      * @param  start
1022      *         The index of the first character in the subsequence
1023      *
1024      * @param  end
1025      *         The index of the character following the last character in the
1026      *         subsequence
1027      *
1028      * @return  This writer
1029      *
1030      * @throws  IndexOutOfBoundsException
1031      *          If <tt>start</tt> or <tt>end</tt> are negative, <tt>start</tt>
1032      *          is greater than <tt>end</tt>, or <tt>end</tt> is greater than
1033      *          <tt>csq.length()</tt>
1034      *
1035      * @since  1.5
1036      */
1037     public PrintWriter append(CharSequence csq, int start, int end) {
1038         CharSequence cs = (csq == null ? "null" : csq);
1039         write(cs.subSequence(start, end).toString());
1040         return this;
1041     }
1042 
1043     /**
1044      * Appends the specified character to this writer.
1045      *
1046      * <p> An invocation of this method of the form <tt>out.append(c)</tt>
1047      * behaves in exactly the same way as the invocation
1048      *
1049      * <pre>
1050      *     out.write(c) </pre>
1051      *
1052      * @param  c
1053      *         The 16-bit character to append
1054      *
1055      * @return  This writer
1056      *
1057      * @since 1.5
1058      */
1059     public PrintWriter append(char c) {
1060         write(c);
1061         return this;
1062     }
1063 }