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