1 /*
   2  * Copyright (c) 1994, 2012, 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.nio.channels.FileChannel;
  29 import sun.nio.ch.FileChannelImpl;
  30 
  31 
  32 /**
  33  * A file output stream is an output stream for writing data to a
  34  * <code>File</code> or to a <code>FileDescriptor</code>. Whether or not
  35  * a file is available or may be created depends upon the underlying
  36  * platform.  Some platforms, in particular, allow a file to be opened
  37  * for writing by only one <tt>FileOutputStream</tt> (or other
  38  * file-writing object) at a time.  In such situations the constructors in
  39  * this class will fail if the file involved is already open.
  40  *
  41  * <p><code>FileOutputStream</code> is meant for writing streams of raw bytes
  42  * such as image data. For writing streams of characters, consider using
  43  * <code>FileWriter</code>.
  44  *
  45  * @author  Arthur van Hoff
  46  * @see     java.io.File
  47  * @see     java.io.FileDescriptor
  48  * @see     java.io.FileInputStream
  49  * @see     java.nio.file.Files#newOutputStream
  50  * @since   JDK1.0
  51  */
  52 public
  53 class FileOutputStream extends OutputStream
  54 {
  55     /**
  56      * The system dependent file descriptor.
  57      */
  58     private final FileDescriptor fd;
  59 
  60     /**
  61      * True if the file is opened for append.
  62      */
  63     private final boolean append;
  64 
  65     /**
  66      * The associated channel, initalized lazily.
  67      */
  68     private FileChannel channel;
  69 
  70     private final Object closeLock = new Object();
  71     private volatile boolean closed = false;
  72 
  73     /**
  74      * Creates a file output stream to write to the file with the
  75      * specified name. A new <code>FileDescriptor</code> object is
  76      * created to represent this file connection.
  77      * <p>
  78      * First, if there is a security manager, its <code>checkWrite</code>
  79      * method is called with <code>name</code> as its argument.
  80      * <p>
  81      * If the file exists but is a directory rather than a regular file, does
  82      * not exist but cannot be created, or cannot be opened for any other
  83      * reason then a <code>FileNotFoundException</code> is thrown.
  84      *
  85      * @param      name   the system-dependent filename
  86      * @exception  FileNotFoundException  if the file exists but is a directory
  87      *                   rather than a regular file, does not exist but cannot
  88      *                   be created, or cannot be opened for any other reason
  89      * @exception  SecurityException  if a security manager exists and its
  90      *               <code>checkWrite</code> method denies write access
  91      *               to the file.
  92      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
  93      */
  94     public FileOutputStream(String name) throws FileNotFoundException {
  95         this(name != null ? new File(name) : null, false);
  96     }
  97 
  98     /**
  99      * Creates a file output stream to write to the file with the specified
 100      * name.  If the second argument is <code>true</code>, then
 101      * bytes will be written to the end of the file rather than the beginning.
 102      * A new <code>FileDescriptor</code> object is created to represent this
 103      * file connection.
 104      * <p>
 105      * First, if there is a security manager, its <code>checkWrite</code>
 106      * method is called with <code>name</code> as its argument.
 107      * <p>
 108      * If the file exists but is a directory rather than a regular file, does
 109      * not exist but cannot be created, or cannot be opened for any other
 110      * reason then a <code>FileNotFoundException</code> is thrown.
 111      *
 112      * @param     name        the system-dependent file name
 113      * @param     append      if <code>true</code>, then bytes will be written
 114      *                   to the end of the file rather than the beginning
 115      * @exception  FileNotFoundException  if the file exists but is a directory
 116      *                   rather than a regular file, does not exist but cannot
 117      *                   be created, or cannot be opened for any other reason.
 118      * @exception  SecurityException  if a security manager exists and its
 119      *               <code>checkWrite</code> method denies write access
 120      *               to the file.
 121      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 122      * @since     JDK1.1
 123      */
 124     public FileOutputStream(String name, boolean append)
 125         throws FileNotFoundException
 126     {
 127         this(name != null ? new File(name) : null, append);
 128     }
 129 
 130     /**
 131      * Creates a file output stream to write to the file represented by
 132      * the specified <code>File</code> object. A new
 133      * <code>FileDescriptor</code> object is created to represent this
 134      * file connection.
 135      * <p>
 136      * First, if there is a security manager, its <code>checkWrite</code>
 137      * method is called with the path represented by the <code>file</code>
 138      * argument as its argument.
 139      * <p>
 140      * If the file exists but is a directory rather than a regular file, does
 141      * not exist but cannot be created, or cannot be opened for any other
 142      * reason then a <code>FileNotFoundException</code> is thrown.
 143      *
 144      * @param      file               the file to be opened for writing.
 145      * @exception  FileNotFoundException  if the file exists but is a directory
 146      *                   rather than a regular file, does not exist but cannot
 147      *                   be created, or cannot be opened for any other reason
 148      * @exception  SecurityException  if a security manager exists and its
 149      *               <code>checkWrite</code> method denies write access
 150      *               to the file.
 151      * @see        java.io.File#getPath()
 152      * @see        java.lang.SecurityException
 153      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 154      */
 155     public FileOutputStream(File file) throws FileNotFoundException {
 156         this(file, false);
 157     }
 158 
 159     /**
 160      * Creates a file output stream to write to the file represented by
 161      * the specified <code>File</code> object. If the second argument is
 162      * <code>true</code>, then bytes will be written to the end of the file
 163      * rather than the beginning. A new <code>FileDescriptor</code> object is
 164      * created to represent this file connection.
 165      * <p>
 166      * First, if there is a security manager, its <code>checkWrite</code>
 167      * method is called with the path represented by the <code>file</code>
 168      * argument as its argument.
 169      * <p>
 170      * If the file exists but is a directory rather than a regular file, does
 171      * not exist but cannot be created, or cannot be opened for any other
 172      * reason then a <code>FileNotFoundException</code> is thrown.
 173      *
 174      * @param      file               the file to be opened for writing.
 175      * @param     append      if <code>true</code>, then bytes will be written
 176      *                   to the end of the file rather than the beginning
 177      * @exception  FileNotFoundException  if the file exists but is a directory
 178      *                   rather than a regular file, does not exist but cannot
 179      *                   be created, or cannot be opened for any other reason
 180      * @exception  SecurityException  if a security manager exists and its
 181      *               <code>checkWrite</code> method denies write access
 182      *               to the file.
 183      * @see        java.io.File#getPath()
 184      * @see        java.lang.SecurityException
 185      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 186      * @since 1.4
 187      */
 188     public FileOutputStream(File file, boolean append)
 189         throws FileNotFoundException
 190     {
 191         String name = (file != null ? file.getPath() : null);
 192         SecurityManager security = System.getSecurityManager();
 193         if (security != null) {
 194             security.checkWrite(name);
 195         }
 196         if (name == null) {
 197             throw new NullPointerException();
 198         }
 199         this.fd = new FileDescriptor();
 200         this.append = append;
 201 
 202         fd.attach(this);
 203         open(name, append);
 204     }
 205 
 206     /**
 207      * Creates a file output stream to write to the specified file
 208      * descriptor, which represents an existing connection to an actual
 209      * file in the file system.
 210      * <p>
 211      * First, if there is a security manager, its <code>checkWrite</code>
 212      * method is called with the file descriptor <code>fdObj</code>
 213      * argument as its argument.
 214      * <p>
 215      * If <code>fdObj</code> is null then a <code>NullPointerException</code>
 216      * is thrown.
 217      * <p>
 218      * This constructor does not throw an exception if <code>fdObj</code>
 219      * is {@link java.io.FileDescriptor#valid() invalid}.
 220      * However, if the methods are invoked on the resulting stream to attempt
 221      * I/O on the stream, an <code>IOException</code> is thrown.
 222      *
 223      * @param      fdObj   the file descriptor to be opened for writing
 224      * @exception  SecurityException  if a security manager exists and its
 225      *               <code>checkWrite</code> method denies
 226      *               write access to the file descriptor
 227      * @see        java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)
 228      */
 229     public FileOutputStream(FileDescriptor fdObj) {
 230         SecurityManager security = System.getSecurityManager();
 231         if (fdObj == null) {
 232             throw new NullPointerException();
 233         }
 234         if (security != null) {
 235             security.checkWrite(fdObj);
 236         }
 237         this.fd = fdObj;
 238         this.append = false;
 239         fd.attach(this);
 240     }
 241 
 242     /**
 243      * Opens a file, with the specified name, for overwriting or appending.
 244      * @param name name of file to be opened
 245      * @param append whether the file is to be opened in append mode
 246      */
 247     private native void open(String name, boolean append)
 248         throws FileNotFoundException;
 249 
 250     /**
 251      * Writes the specified byte to this file output stream.
 252      *
 253      * @param   b   the byte to be written.
 254      * @param   append   {@code true} if the write operation first
 255      *     advances the position to the end of file
 256      */
 257     private native void write(int b, boolean append) throws IOException;
 258 
 259     /**
 260      * Writes the specified byte to this file output stream. Implements
 261      * the <code>write</code> method of <code>OutputStream</code>.
 262      *
 263      * @param      b   the byte to be written.
 264      * @exception  IOException  if an I/O error occurs.
 265      */
 266     public void write(int b) throws IOException {
 267         write(b, append);
 268     }
 269 
 270     /**
 271      * Writes a sub array as a sequence of bytes.
 272      * @param b the data to be written
 273      * @param off the start offset in the data
 274      * @param len the number of bytes that are written
 275      * @param append {@code true} to first advance the position to the
 276      *     end of file
 277      * @exception IOException If an I/O error has occurred.
 278      */
 279     private native void writeBytes(byte b[], int off, int len, boolean append)
 280         throws IOException;
 281 
 282     /**
 283      * Writes <code>b.length</code> bytes from the specified byte array
 284      * to this file output stream.
 285      *
 286      * @param      b   the data.
 287      * @exception  IOException  if an I/O error occurs.
 288      */
 289     public void write(byte b[]) throws IOException {
 290         writeBytes(b, 0, b.length, append);
 291     }
 292 
 293     /**
 294      * Writes <code>len</code> bytes from the specified byte array
 295      * starting at offset <code>off</code> to this file output stream.
 296      *
 297      * @param      b     the data.
 298      * @param      off   the start offset in the data.
 299      * @param      len   the number of bytes to write.
 300      * @exception  IOException  if an I/O error occurs.
 301      */
 302     public void write(byte b[], int off, int len) throws IOException {
 303         writeBytes(b, off, len, append);
 304     }
 305 
 306     /**
 307      * Closes this file output stream and releases any system resources
 308      * associated with this stream. This file output stream may no longer
 309      * be used for writing bytes.
 310      *
 311      * <p> If this stream has an associated channel then the channel is closed
 312      * as well.
 313      *
 314      * @exception  IOException  if an I/O error occurs.
 315      *
 316      * @revised 1.4
 317      * @spec JSR-51
 318      */
 319     public void close() throws IOException {
 320         synchronized (closeLock) {
 321             if (closed) {
 322                 return;
 323             }
 324             closed = true;
 325         }
 326 
 327         if (channel != null) {
 328             channel.close();
 329         }
 330         fd.closeAll(new Closeable() {
 331             public void close() throws IOException {
 332                close0();
 333            }
 334         });
 335     }
 336 
 337     /**
 338      * Returns the file descriptor associated with this stream.
 339      *
 340      * @return  the <code>FileDescriptor</code> object that represents
 341      *          the connection to the file in the file system being used
 342      *          by this <code>FileOutputStream</code> object.
 343      *
 344      * @exception  IOException  if an I/O error occurs.
 345      * @see        java.io.FileDescriptor
 346      */
 347      public final FileDescriptor getFD()  throws IOException {
 348         if (fd != null) {
 349             return fd;
 350         }
 351         throw new IOException();
 352      }
 353 
 354     /**
 355      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
 356      * object associated with this file output stream. </p>
 357      *
 358      * <p> The initial {@link java.nio.channels.FileChannel#position()
 359      * </code>position<code>} of the returned channel will be equal to the
 360      * number of bytes written to the file so far unless this stream is in
 361      * append mode, in which case it will be equal to the size of the file.
 362      * Writing bytes to this stream will increment the channel's position
 363      * accordingly.  Changing the channel's position, either explicitly or by
 364      * writing, will change this stream's file position.
 365      *
 366      * @return  the file channel associated with this file output stream
 367      *
 368      * @since 1.4
 369      * @spec JSR-51
 370      */
 371     public FileChannel getChannel() {
 372         synchronized (this) {
 373             if (channel == null) {
 374                 channel = FileChannelImpl.open(fd, false, true, append, this);
 375             }
 376             return channel;
 377         }
 378     }
 379 
 380     /**
 381      * Cleans up the connection to the file, and ensures that the
 382      * <code>close</code> method of this file output stream is
 383      * called when there are no more references to this stream.
 384      *
 385      * @exception  IOException  if an I/O error occurs.
 386      * @see        java.io.FileInputStream#close()
 387      */
 388     protected void finalize() throws IOException {
 389         if (fd != null) {
 390             if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
 391                 flush();
 392             } else {
 393                 /* if fd is shared, the references in FileDescriptor
 394                  * will ensure that finalizer is only called when
 395                  * safe to do so. All references using the fd have
 396                  * become unreachable. We can call close()
 397                  */
 398                 close();
 399             }
 400         }
 401     }
 402 
 403     private native void close0() throws IOException;
 404 
 405     private static native void initIDs();
 406 
 407     static {
 408         initIDs();
 409     }
 410 
 411 }