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