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

Print this page




   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 
  31 /**
  32  * Prints formatted representations of objects to a text-output stream.  This
  33  * class implements all of the <tt>print</tt> methods found in {@link
  34  * PrintStream}.  It does not contain methods for writing raw bytes, for which
  35  * a program should use unencoded byte streams.
  36  *
  37  * <p> Unlike the {@link PrintStream} class, if automatic flushing is enabled
  38  * it will be done only when one of the <tt>println</tt>, <tt>printf</tt>, or
  39  * <tt>format</tt> methods is invoked, rather than whenever a newline character
  40  * happens to be output.  These methods use the platform's own notion of line
  41  * separator rather than the newline character.
  42  *
  43  * <p> Methods in this class never throw I/O exceptions, although some of its
  44  * constructors may.  The client may inquire as to whether any errors have
  45  * occurred by invoking {@link #checkError checkError()}.
  46  *
  47  * @author      Frank Yellin
  48  * @author      Mark Reinhold
  49  * @since       JDK1.1
  50  */
  51 
  52 public class PrintWriter extends Writer {
  53 
  54     /**
  55      * The underlying character-output stream of this
  56      * <code>PrintWriter</code>.
  57      *
  58      * @since 1.2
  59      */
  60     protected Writer out;
  61 
  62     private boolean autoFlush = false;
  63     private boolean trouble = false;
  64     private Formatter formatter;
  65     private PrintStream psOut = null;
  66 
  67     /**
  68      * Line separator string.  This is the value of the line.separator
  69      * property at the moment that the stream was created.
  70      */
  71     private String lineSeparator;
  72 
  73     /**

















  74      * Creates a new PrintWriter, without automatic line flushing.
  75      *
  76      * @param  out        A character-output stream
  77      */
  78     public PrintWriter (Writer out) {
  79         this(out, false);
  80     }
  81 
  82     /**
  83      * Creates a new PrintWriter.
  84      *
  85      * @param  out        A character-output stream
  86      * @param  autoFlush  A boolean; if true, the <tt>println</tt>,
  87      *                    <tt>printf</tt>, or <tt>format</tt> methods will
  88      *                    flush the output buffer
  89      */
  90     public PrintWriter(Writer out,
  91                        boolean autoFlush) {
  92         super(out);
  93         this.out = out;


 147      *         written to the file and is buffered.
 148      *
 149      * @throws  FileNotFoundException
 150      *          If the given string does not denote an existing, writable
 151      *          regular file and a new regular file of that name cannot be
 152      *          created, or if some other error occurs while opening or
 153      *          creating the file
 154      *
 155      * @throws  SecurityException
 156      *          If a security manager is present and {@link
 157      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 158      *          access to the file
 159      *
 160      * @since  1.5
 161      */
 162     public PrintWriter(String fileName) throws FileNotFoundException {
 163         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
 164              false);
 165     }
 166 






 167     /**
 168      * Creates a new PrintWriter, without automatic line flushing, with the
 169      * specified file name and charset.  This convenience constructor creates
 170      * the necessary intermediate {@link java.io.OutputStreamWriter
 171      * OutputStreamWriter}, which will encode characters using the provided
 172      * charset.
 173      *
 174      * @param  fileName
 175      *         The name of the file to use as the destination of this writer.
 176      *         If the file exists then it will be truncated to zero size;
 177      *         otherwise, a new file will be created.  The output will be
 178      *         written to the file and is buffered.
 179      *
 180      * @param  csn
 181      *         The name of a supported {@linkplain java.nio.charset.Charset
 182      *         charset}
 183      *
 184      * @throws  FileNotFoundException
 185      *          If the given string does not denote an existing, writable
 186      *          regular file and a new regular file of that name cannot be
 187      *          created, or if some other error occurs while opening or
 188      *          creating the file
 189      *
 190      * @throws  SecurityException
 191      *          If a security manager is present and {@link
 192      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 193      *          access to the file
 194      *
 195      * @throws  UnsupportedEncodingException
 196      *          If the named charset is not supported
 197      *
 198      * @since  1.5
 199      */
 200     public PrintWriter(String fileName, String csn)
 201         throws FileNotFoundException, UnsupportedEncodingException
 202     {
 203         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), csn)),
 204              false);
 205     }
 206 
 207     /**
 208      * Creates a new PrintWriter, without automatic line flushing, with the
 209      * specified file.  This convenience constructor creates the necessary
 210      * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter},
 211      * which will encode characters using the {@linkplain
 212      * java.nio.charset.Charset#defaultCharset() default charset} for this
 213      * instance of the Java virtual machine.
 214      *
 215      * @param  file
 216      *         The file to use as the destination of this writer.  If the file
 217      *         exists then it will be truncated to zero size; otherwise, a new
 218      *         file will be created.  The output will be written to the file
 219      *         and is buffered.
 220      *
 221      * @throws  FileNotFoundException
 222      *          If the given file object does not denote an existing, writable
 223      *          regular file and a new regular file of that name cannot be
 224      *          created, or if some other error occurs while opening or


 255      *
 256      * @throws  FileNotFoundException
 257      *          If the given file object does not denote an existing, writable
 258      *          regular file and a new regular file of that name cannot be
 259      *          created, or if some other error occurs while opening or
 260      *          creating the file
 261      *
 262      * @throws  SecurityException
 263      *          If a security manager is present and {@link
 264      *          SecurityManager#checkWrite checkWrite(file.getPath())}
 265      *          denies write access to the file
 266      *
 267      * @throws  UnsupportedEncodingException
 268      *          If the named charset is not supported
 269      *
 270      * @since  1.5
 271      */
 272     public PrintWriter(File file, String csn)
 273         throws FileNotFoundException, UnsupportedEncodingException
 274     {
 275         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), csn)),
 276              false);
 277     }
 278 
 279     /** Checks to make sure that the stream has not been closed */
 280     private void ensureOpen() throws IOException {
 281         if (out == null)
 282             throw new IOException("Stream closed");
 283     }
 284 
 285     /**
 286      * Flushes the stream.
 287      * @see #checkError()
 288      */
 289     public void flush() {
 290         try {
 291             synchronized (lock) {
 292                 ensureOpen();
 293                 out.flush();
 294             }
 295         }
 296         catch (IOException x) {




   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 
  34 /**
  35  * Prints formatted representations of objects to a text-output stream.  This
  36  * class implements all of the <tt>print</tt> methods found in {@link
  37  * PrintStream}.  It does not contain methods for writing raw bytes, for which
  38  * a program should use unencoded byte streams.
  39  *
  40  * <p> Unlike the {@link PrintStream} class, if automatic flushing is enabled
  41  * it will be done only when one of the <tt>println</tt>, <tt>printf</tt>, or
  42  * <tt>format</tt> methods is invoked, rather than whenever a newline character
  43  * happens to be output.  These methods use the platform's own notion of line
  44  * separator rather than the newline character.
  45  *
  46  * <p> Methods in this class never throw I/O exceptions, although some of its
  47  * constructors may.  The client may inquire as to whether any errors have
  48  * occurred by invoking {@link #checkError checkError()}.
  49  *
  50  * @author      Frank Yellin
  51  * @author      Mark Reinhold
  52  * @since       JDK1.1
  53  */
  54 
  55 public class PrintWriter extends Writer {
  56 
  57     /**
  58      * The underlying character-output stream of this
  59      * <code>PrintWriter</code>.
  60      *
  61      * @since 1.2
  62      */
  63     protected Writer out;
  64 
  65     private final boolean autoFlush;
  66     private boolean trouble = false;
  67     private Formatter formatter;
  68     private PrintStream psOut = null;
  69 
  70     /**
  71      * Line separator string.  This is the value of the line.separator
  72      * property at the moment that the stream was created.
  73      */
  74     private final String lineSeparator;
  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      */
  81     private static Charset toCharset(String csn)
  82             throws UnsupportedEncodingException {
  83         Objects.nonNull(csn, "charsetName");
  84         try {
  85             return Charset.forName(csn);
  86         } catch (IllegalCharsetNameException unused) {
  87             /* swallow this exception since UnsupportedEncodingException
  88              * will be thrown */
  89         }
  90         throw new UnsupportedEncodingException(csn);
  91     }
  92 
  93     /**
  94      * Creates a new PrintWriter, without automatic line flushing.
  95      *
  96      * @param  out        A character-output stream
  97      */
  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 <tt>println</tt>,
 107      *                    <tt>printf</tt>, or <tt>format</tt> methods will
 108      *                    flush the output buffer
 109      */
 110     public PrintWriter(Writer out,
 111                        boolean autoFlush) {
 112         super(out);
 113         this.out = out;


 167      *         written to the file and is buffered.
 168      *
 169      * @throws  FileNotFoundException
 170      *          If the given string does not denote an existing, writable
 171      *          regular file and a new regular file of that name cannot be
 172      *          created, or if some other error occurs while opening or
 173      *          creating the file
 174      *
 175      * @throws  SecurityException
 176      *          If a security manager is present and {@link
 177      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 178      *          access to the file
 179      *
 180      * @since  1.5
 181      */
 182     public PrintWriter(String fileName) throws FileNotFoundException {
 183         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
 184              false);
 185     }
 186 
 187     /* Private constructor*/
 188     private PrintWriter(Charset charset, File file) throws FileNotFoundException {
 189         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),
 190              false);
 191     }
 192 
 193     /**
 194      * Creates a new PrintWriter, without automatic line flushing, with the
 195      * specified file name and charset.  This convenience constructor creates
 196      * the necessary intermediate {@link java.io.OutputStreamWriter
 197      * OutputStreamWriter}, which will encode characters using the provided
 198      * charset.
 199      *
 200      * @param  fileName
 201      *         The name of the file to use as the destination of this writer.
 202      *         If the file exists then it will be truncated to zero size;
 203      *         otherwise, a new file will be created.  The output will be
 204      *         written to the file and is buffered.
 205      *
 206      * @param  csn
 207      *         The name of a supported {@linkplain java.nio.charset.Charset
 208      *         charset}
 209      *
 210      * @throws  FileNotFoundException
 211      *          If the given string does not denote an existing, writable
 212      *          regular file and a new regular file of that name cannot be
 213      *          created, or if some other error occurs while opening or
 214      *          creating the file
 215      *
 216      * @throws  SecurityException
 217      *          If a security manager is present and {@link
 218      *          SecurityManager#checkWrite checkWrite(fileName)} denies write
 219      *          access to the file
 220      *
 221      * @throws  UnsupportedEncodingException
 222      *          If the named charset is not supported
 223      *
 224      * @since  1.5
 225      */
 226     public PrintWriter(String fileName, String csn)
 227         throws FileNotFoundException, UnsupportedEncodingException
 228     {
 229         this(toCharset(csn), new File(fileName));

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


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

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