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