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