< prev index next >

src/java.base/share/classes/java/io/PrintWriter.java

Print this page


   1 /*
   2  * Copyright (c) 1996, 2016, 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


  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  * @author      Frank Yellin
  52  * @author      Mark Reinhold
  53  * @since       1.1
  54  */
  55 
  56 public class PrintWriter extends Writer {
  57 
  58     /**
  59      * The underlying character-output stream of this
  60      * {@code PrintWriter}.
  61      *
  62      * @since 1.2
  63      */
  64     protected Writer out;
  65 
  66     private final boolean autoFlush;
  67     private boolean trouble = false;
  68     private Formatter formatter;
  69     private PrintStream psOut = null;
  70 


 120      * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 121      */
 122     public PrintWriter(OutputStream out) {
 123         this(out, false);
 124     }
 125 
 126     /**
 127      * Creates a new PrintWriter from an existing OutputStream.  This
 128      * convenience constructor creates the necessary intermediate
 129      * OutputStreamWriter, which will convert characters into bytes using the
 130      * default character encoding.
 131      *
 132      * @param  out        An output stream
 133      * @param  autoFlush  A boolean; if true, the {@code println},
 134      *                    {@code printf}, or {@code format} methods will
 135      *                    flush the output buffer
 136      *
 137      * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 138      */
 139     public PrintWriter(OutputStream out, boolean autoFlush) {
 140         this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);



















 141 
 142         // save print stream for error propagation
 143         if (out instanceof java.io.PrintStream) {
 144             psOut = (PrintStream) out;
 145         }
 146     }
 147 
 148     /**
 149      * Creates a new PrintWriter, without automatic line flushing, with the
 150      * specified file name.  This convenience constructor creates the necessary
 151      * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
 152      * which will encode characters using the {@linkplain
 153      * java.nio.charset.Charset#defaultCharset() default charset} for this
 154      * instance of the Java virtual machine.
 155      *
 156      * @param  fileName
 157      *         The name of the file to use as the destination of this writer.
 158      *         If the file exists then it will be truncated to zero size;
 159      *         otherwise, a new file will be created.  The output will be
 160      *         written to the file and is buffered.


 209      *          creating the file
 210      *
 211      * @throws  SecurityException
 212      *          If a security manager is present and {@link
 213      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 214      *          access to the file
 215      *
 216      * @throws  UnsupportedEncodingException
 217      *          If the named charset is not supported
 218      *
 219      * @since  1.5
 220      */
 221     public PrintWriter(String fileName, String csn)
 222         throws FileNotFoundException, UnsupportedEncodingException
 223     {
 224         this(toCharset(csn), new File(fileName));
 225     }
 226 
 227     /**
 228      * Creates a new PrintWriter, without automatic line flushing, with the






























 229      * specified file.  This convenience constructor creates the necessary
 230      * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
 231      * which will encode characters using the {@linkplain
 232      * java.nio.charset.Charset#defaultCharset() default charset} for this
 233      * instance of the Java virtual machine.
 234      *
 235      * @param  file
 236      *         The file to use as the destination of this writer.  If the file
 237      *         exists then it will be truncated to zero size; otherwise, a new
 238      *         file will be created.  The output will be written to the file
 239      *         and is buffered.
 240      *
 241      * @throws  FileNotFoundException
 242      *          If the given file object does not denote an existing, writable
 243      *          regular file and a new regular file of that name cannot be
 244      *          created, or if some other error occurs while opening or
 245      *          creating the file
 246      *
 247      * @throws  SecurityException
 248      *          If a security manager is present and {@link


 276      * @throws  FileNotFoundException
 277      *          If the given file object does not denote an existing, writable
 278      *          regular file and a new regular file of that name cannot be
 279      *          created, or if some other error occurs while opening or
 280      *          creating the file
 281      *
 282      * @throws  SecurityException
 283      *          If a security manager is present and {@link
 284      *          SecurityManager#checkWrite checkWrite(file.getPath())}
 285      *          denies write access to the file
 286      *
 287      * @throws  UnsupportedEncodingException
 288      *          If the named charset is not supported
 289      *
 290      * @since  1.5
 291      */
 292     public PrintWriter(File file, String csn)
 293         throws FileNotFoundException, UnsupportedEncodingException
 294     {
 295         this(toCharset(csn), file);






























 296     }
 297 
 298     /** Checks to make sure that the stream has not been closed */
 299     private void ensureOpen() throws IOException {
 300         if (out == null)
 301             throw new IOException("Stream closed");
 302     }
 303 
 304     /**
 305      * Flushes the stream.
 306      * @see #checkError()
 307      */
 308     public void flush() {
 309         try {
 310             synchronized (lock) {
 311                 ensureOpen();
 312                 out.flush();
 313             }
 314         }
 315         catch (IOException x) {


   1 /*
   2  * Copyright (c) 1996, 2017, 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


  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 


 125      * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 126      */
 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      */
 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      */
 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.


 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      */
 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      */
 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


 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      */
 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      */
 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 */
 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      */
 392     public void flush() {
 393         try {
 394             synchronized (lock) {
 395                 ensureOpen();
 396                 out.flush();
 397             }
 398         }
 399         catch (IOException x) {


< prev index next >