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