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