1 /*
2  * Copyright (c) 1996, 2019, 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      */
toCharset(String csn)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      */
PrintWriter(Writer out)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      */
PrintWriter(Writer out, boolean autoFlush)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      */
PrintWriter(OutputStream out)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      */
PrintWriter(OutputStream out, boolean autoFlush)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      */
PrintWriter(OutputStream out, boolean autoFlush, Charset charset)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      */
PrintWriter(String fileName)199     public PrintWriter(String fileName) throws FileNotFoundException {
200         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
201              false);
202     }
203 
204     /* Private constructor */
PrintWriter(Charset charset, File file)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      */
PrintWriter(String fileName, String csn)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      */
PrintWriter(String fileName, Charset charset)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      */
PrintWriter(File file)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      */
PrintWriter(File file, String csn)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      */
PrintWriter(File file, Charset charset)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 */
ensureOpen()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      */
flush()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      */
close()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      */
checkError()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      */
setError()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      */
clearError()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      */
write(int c)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      */
write(char buf[], int off, int len)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      */
write(char buf[])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      */
write(String s, int off, int len)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      */
write(String s)558     public void write(String s) {
559         write(s, 0, s.length());
560     }
561 
newLine()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      */
print(boolean b)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      */
print(char c)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      */
print(int i)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      */
print(long l)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      */
print(float f)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      */
print(double d)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      */
print(char s[])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      */
print(String s)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      */
print(Object obj)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 is {@link System#lineSeparator()} and is not necessarily
708      * a single newline character ({@code '\n'}).
709      */
println()710     public void println() {
711         newLine();
712     }
713 
714     /**
715      * Prints a boolean value and then terminates the line.  This method behaves
716      * as though it invokes {@link #print(boolean)} and then
717      * {@link #println()}.
718      *
719      * @param x the {@code boolean} value to be printed
720      */
println(boolean x)721     public void println(boolean x) {
722         synchronized (lock) {
723             print(x);
724             println();
725         }
726     }
727 
728     /**
729      * Prints a character and then terminates the line.  This method behaves as
730      * though it invokes {@link #print(char)} and then {@link
731      * #println()}.
732      *
733      * @param x the {@code char} value to be printed
734      */
println(char x)735     public void println(char x) {
736         synchronized (lock) {
737             print(x);
738             println();
739         }
740     }
741 
742     /**
743      * Prints an integer and then terminates the line.  This method behaves as
744      * though it invokes {@link #print(int)} and then {@link
745      * #println()}.
746      *
747      * @param x the {@code int} value to be printed
748      */
println(int x)749     public void println(int x) {
750         synchronized (lock) {
751             print(x);
752             println();
753         }
754     }
755 
756     /**
757      * Prints a long integer and then terminates the line.  This method behaves
758      * as though it invokes {@link #print(long)} and then
759      * {@link #println()}.
760      *
761      * @param x the {@code long} value to be printed
762      */
println(long x)763     public void println(long x) {
764         synchronized (lock) {
765             print(x);
766             println();
767         }
768     }
769 
770     /**
771      * Prints a floating-point number and then terminates the line.  This method
772      * behaves as though it invokes {@link #print(float)} and then
773      * {@link #println()}.
774      *
775      * @param x the {@code float} value to be printed
776      */
println(float x)777     public void println(float x) {
778         synchronized (lock) {
779             print(x);
780             println();
781         }
782     }
783 
784     /**
785      * Prints a double-precision floating-point number and then terminates the
786      * line.  This method behaves as though it invokes {@link
787      * #print(double)} and then {@link #println()}.
788      *
789      * @param x the {@code double} value to be printed
790      */
println(double x)791     public void println(double x) {
792         synchronized (lock) {
793             print(x);
794             println();
795         }
796     }
797 
798     /**
799      * Prints an array of characters and then terminates the line.  This method
800      * behaves as though it invokes {@link #print(char[])} and then
801      * {@link #println()}.
802      *
803      * @param x the array of {@code char} values to be printed
804      */
println(char x[])805     public void println(char x[]) {
806         synchronized (lock) {
807             print(x);
808             println();
809         }
810     }
811 
812     /**
813      * Prints a String and then terminates the line.  This method behaves as
814      * though it invokes {@link #print(String)} and then
815      * {@link #println()}.
816      *
817      * @param x the {@code String} value to be printed
818      */
println(String x)819     public void println(String x) {
820         synchronized (lock) {
821             print(x);
822             println();
823         }
824     }
825 
826     /**
827      * Prints an Object and then terminates the line.  This method calls
828      * at first String.valueOf(x) to get the printed object's string value,
829      * then behaves as
830      * though it invokes {@link #print(String)} and then
831      * {@link #println()}.
832      *
833      * @param x  The {@code Object} to be printed.
834      */
println(Object x)835     public void println(Object x) {
836         String s = String.valueOf(x);
837         synchronized (lock) {
838             print(s);
839             println();
840         }
841     }
842 
843     /**
844      * A convenience method to write a formatted string to this writer using
845      * the specified format string and arguments.  If automatic flushing is
846      * enabled, calls to this method will flush the output buffer.
847      *
848      * <p> An invocation of this method of the form
849      * {@code out.printf(format, args)}
850      * behaves in exactly the same way as the invocation
851      *
852      * <pre>{@code
853      *     out.format(format, args)
854      * }</pre>
855      *
856      * @param  format
857      *         A format string as described in <a
858      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
859      *
860      * @param  args
861      *         Arguments referenced by the format specifiers in the format
862      *         string.  If there are more arguments than format specifiers, the
863      *         extra arguments are ignored.  The number of arguments is
864      *         variable and may be zero.  The maximum number of arguments is
865      *         limited by the maximum dimension of a Java array as defined by
866      *         <cite>The Java Virtual Machine Specification</cite>.
867      *         The behaviour on a
868      *         {@code null} argument depends on the <a
869      *         href="../util/Formatter.html#syntax">conversion</a>.
870      *
871      * @throws  java.util.IllegalFormatException
872      *          If a format string contains an illegal syntax, a format
873      *          specifier that is incompatible with the given arguments,
874      *          insufficient arguments given the format string, or other
875      *          illegal conditions.  For specification of all possible
876      *          formatting errors, see the <a
877      *          href="../util/Formatter.html#detail">Details</a> section of the
878      *          formatter class specification.
879      *
880      * @throws  NullPointerException
881      *          If the {@code format} is {@code null}
882      *
883      * @return  This writer
884      *
885      * @since  1.5
886      */
printf(String format, Object ... args)887     public PrintWriter printf(String format, Object ... args) {
888         return format(format, args);
889     }
890 
891     /**
892      * A convenience method to write a formatted string to this writer using
893      * the specified format string and arguments.  If automatic flushing is
894      * enabled, calls to this method will flush the output buffer.
895      *
896      * <p> An invocation of this method of the form
897      * {@code out.printf(l, format, args)}
898      * behaves in exactly the same way as the invocation
899      *
900      * <pre>{@code
901      *     out.format(l, format, args)
902      * }</pre>
903      *
904      * @param  l
905      *         The {@linkplain java.util.Locale locale} to apply during
906      *         formatting.  If {@code l} is {@code null} then no localization
907      *         is applied.
908      *
909      * @param  format
910      *         A format string as described in <a
911      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
912      *
913      * @param  args
914      *         Arguments referenced by the format specifiers in the format
915      *         string.  If there are more arguments than format specifiers, the
916      *         extra arguments are ignored.  The number of arguments is
917      *         variable and may be zero.  The maximum number of arguments is
918      *         limited by the maximum dimension of a Java array as defined by
919      *         <cite>The Java Virtual Machine Specification</cite>.
920      *         The behaviour on a
921      *         {@code null} argument depends on the <a
922      *         href="../util/Formatter.html#syntax">conversion</a>.
923      *
924      * @throws  java.util.IllegalFormatException
925      *          If a format string contains an illegal syntax, a format
926      *          specifier that is incompatible with the given arguments,
927      *          insufficient arguments given the format string, or other
928      *          illegal conditions.  For specification of all possible
929      *          formatting errors, see the <a
930      *          href="../util/Formatter.html#detail">Details</a> section of the
931      *          formatter class specification.
932      *
933      * @throws  NullPointerException
934      *          If the {@code format} is {@code null}
935      *
936      * @return  This writer
937      *
938      * @since  1.5
939      */
printf(Locale l, String format, Object ... args)940     public PrintWriter printf(Locale l, String format, Object ... args) {
941         return format(l, format, args);
942     }
943 
944     /**
945      * Writes a formatted string to this writer using the specified format
946      * string and arguments.  If automatic flushing is enabled, calls to this
947      * method will flush the output buffer.
948      *
949      * <p> The locale always used is the one returned by {@link
950      * java.util.Locale#getDefault() Locale.getDefault()}, regardless of any
951      * previous invocations of other formatting methods on this object.
952      *
953      * @param  format
954      *         A format string as described in <a
955      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
956      *
957      * @param  args
958      *         Arguments referenced by the format specifiers in the format
959      *         string.  If there are more arguments than format specifiers, the
960      *         extra arguments are ignored.  The number of arguments is
961      *         variable and may be zero.  The maximum number of arguments is
962      *         limited by the maximum dimension of a Java array as defined by
963      *         <cite>The Java Virtual Machine Specification</cite>.
964      *         The behaviour on a
965      *         {@code null} argument depends on the <a
966      *         href="../util/Formatter.html#syntax">conversion</a>.
967      *
968      * @throws  java.util.IllegalFormatException
969      *          If a format string contains an illegal syntax, a format
970      *          specifier that is incompatible with the given arguments,
971      *          insufficient arguments given the format string, or other
972      *          illegal conditions.  For specification of all possible
973      *          formatting errors, see the <a
974      *          href="../util/Formatter.html#detail">Details</a> section of the
975      *          Formatter class specification.
976      *
977      * @throws  NullPointerException
978      *          If the {@code format} is {@code null}
979      *
980      * @return  This writer
981      *
982      * @since  1.5
983      */
format(String format, Object ... args)984     public PrintWriter format(String format, Object ... args) {
985         try {
986             synchronized (lock) {
987                 ensureOpen();
988                 if ((formatter == null)
989                     || (formatter.locale() != Locale.getDefault()))
990                     formatter = new Formatter(this);
991                 formatter.format(Locale.getDefault(), format, args);
992                 if (autoFlush)
993                     out.flush();
994             }
995         } catch (InterruptedIOException x) {
996             Thread.currentThread().interrupt();
997         } catch (IOException x) {
998             trouble = true;
999         }
1000         return this;
1001     }
1002 
1003     /**
1004      * Writes a formatted string to this writer using the specified format
1005      * string and arguments.  If automatic flushing is enabled, calls to this
1006      * method will flush the output buffer.
1007      *
1008      * @param  l
1009      *         The {@linkplain java.util.Locale locale} to apply during
1010      *         formatting.  If {@code l} is {@code null} then no localization
1011      *         is applied.
1012      *
1013      * @param  format
1014      *         A format string as described in <a
1015      *         href="../util/Formatter.html#syntax">Format string syntax</a>.
1016      *
1017      * @param  args
1018      *         Arguments referenced by the format specifiers in the format
1019      *         string.  If there are more arguments than format specifiers, the
1020      *         extra arguments are ignored.  The number of arguments is
1021      *         variable and may be zero.  The maximum number of arguments is
1022      *         limited by the maximum dimension of a Java array as defined by
1023      *         <cite>The Java Virtual Machine Specification</cite>.
1024      *         The behaviour on a
1025      *         {@code null} argument depends on the <a
1026      *         href="../util/Formatter.html#syntax">conversion</a>.
1027      *
1028      * @throws  java.util.IllegalFormatException
1029      *          If a format string contains an illegal syntax, a format
1030      *          specifier that is incompatible with the given arguments,
1031      *          insufficient arguments given the format string, or other
1032      *          illegal conditions.  For specification of all possible
1033      *          formatting errors, see the <a
1034      *          href="../util/Formatter.html#detail">Details</a> section of the
1035      *          formatter class specification.
1036      *
1037      * @throws  NullPointerException
1038      *          If the {@code format} is {@code null}
1039      *
1040      * @return  This writer
1041      *
1042      * @since  1.5
1043      */
format(Locale l, String format, Object ... args)1044     public PrintWriter format(Locale l, String format, Object ... args) {
1045         try {
1046             synchronized (lock) {
1047                 ensureOpen();
1048                 if ((formatter == null) || (formatter.locale() != l))
1049                     formatter = new Formatter(this, l);
1050                 formatter.format(l, format, args);
1051                 if (autoFlush)
1052                     out.flush();
1053             }
1054         } catch (InterruptedIOException x) {
1055             Thread.currentThread().interrupt();
1056         } catch (IOException x) {
1057             trouble = true;
1058         }
1059         return this;
1060     }
1061 
1062     /**
1063      * Appends the specified character sequence to this writer.
1064      *
1065      * <p> An invocation of this method of the form {@code out.append(csq)}
1066      * behaves in exactly the same way as the invocation
1067      *
1068      * <pre>{@code
1069      *     out.write(csq.toString())
1070      * }</pre>
1071      *
1072      * <p> Depending on the specification of {@code toString} for the
1073      * character sequence {@code csq}, the entire sequence may not be
1074      * appended. For instance, invoking the {@code toString} method of a
1075      * character buffer will return a subsequence whose content depends upon
1076      * the buffer's position and limit.
1077      *
1078      * @param  csq
1079      *         The character sequence to append.  If {@code csq} is
1080      *         {@code null}, then the four characters {@code "null"} are
1081      *         appended to this writer.
1082      *
1083      * @return  This writer
1084      *
1085      * @since  1.5
1086      */
append(CharSequence csq)1087     public PrintWriter append(CharSequence csq) {
1088         write(String.valueOf(csq));
1089         return this;
1090     }
1091 
1092     /**
1093      * Appends a subsequence of the specified character sequence to this writer.
1094      *
1095      * <p> An invocation of this method of the form
1096      * {@code out.append(csq, start, end)}
1097      * when {@code csq} is not {@code null}, behaves in
1098      * exactly the same way as the invocation
1099      *
1100      * <pre>{@code
1101      *     out.write(csq.subSequence(start, end).toString())
1102      * }</pre>
1103      *
1104      * @param  csq
1105      *         The character sequence from which a subsequence will be
1106      *         appended.  If {@code csq} is {@code null}, then characters
1107      *         will be appended as if {@code csq} contained the four
1108      *         characters {@code "null"}.
1109      *
1110      * @param  start
1111      *         The index of the first character in the subsequence
1112      *
1113      * @param  end
1114      *         The index of the character following the last character in the
1115      *         subsequence
1116      *
1117      * @return  This writer
1118      *
1119      * @throws  IndexOutOfBoundsException
1120      *          If {@code start} or {@code end} are negative, {@code start}
1121      *          is greater than {@code end}, or {@code end} is greater than
1122      *          {@code csq.length()}
1123      *
1124      * @since  1.5
1125      */
append(CharSequence csq, int start, int end)1126     public PrintWriter append(CharSequence csq, int start, int end) {
1127         if (csq == null) csq = "null";
1128         return append(csq.subSequence(start, end));
1129     }
1130 
1131     /**
1132      * Appends the specified character to this writer.
1133      *
1134      * <p> An invocation of this method of the form {@code out.append(c)}
1135      * behaves in exactly the same way as the invocation
1136      *
1137      * <pre>{@code
1138      *     out.write(c)
1139      * }</pre>
1140      *
1141      * @param  c
1142      *         The 16-bit character to append
1143      *
1144      * @return  This writer
1145      *
1146      * @since 1.5
1147      */
append(char c)1148     public PrintWriter append(char c) {
1149         write(c);
1150         return this;
1151     }
1152 }
1153