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