1 /*
   2  * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.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, initialized lazily.
  67      */
  68     private FileChannel channel;
  69 
  70     /**
  71      * The path of the referenced file (null if the stream is created with a file descriptor)
  72      */
  73     private final String path;
  74 
  75     private final Object closeLock = new Object();
  76     private volatile boolean closed = false;
  77 
  78     /**
  79      * Creates a file output stream to write to the file with the
  80      * specified name. A new <code>FileDescriptor</code> object is
  81      * created to represent this file connection.
  82      * <p>
  83      * First, if there is a security manager, its <code>checkWrite</code>
  84      * method is called with <code>name</code> as its argument.
  85      * <p>
  86      * If the file exists but is a directory rather than a regular file, does
  87      * not exist but cannot be created, or cannot be opened for any other
  88      * reason then a <code>FileNotFoundException</code> is thrown.
  89      *
  90      * @param      name   the system-dependent filename
  91      * @exception  FileNotFoundException  if the file exists but is a directory
  92      *                   rather than a regular file, does not exist but cannot
  93      *                   be created, or cannot be opened for any other reason
  94      * @exception  SecurityException  if a security manager exists and its
  95      *               <code>checkWrite</code> method denies write access
  96      *               to the file.
  97      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
  98      */
  99     public FileOutputStream(String name) throws FileNotFoundException {
 100         this(name != null ? new File(name) : null, false);
 101     }
 102 
 103     /**
 104      * Creates a file output stream to write to the file with the specified
 105      * name.  If the second argument is <code>true</code>, then
 106      * bytes will be written to the end of the file rather than the beginning.
 107      * A new <code>FileDescriptor</code> object is created to represent this
 108      * file connection.
 109      * <p>
 110      * First, if there is a security manager, its <code>checkWrite</code>
 111      * method is called with <code>name</code> as its argument.
 112      * <p>
 113      * If the file exists but is a directory rather than a regular file, does
 114      * not exist but cannot be created, or cannot be opened for any other
 115      * reason then a <code>FileNotFoundException</code> is thrown.
 116      *
 117      * @param     name        the system-dependent file name
 118      * @param     append      if <code>true</code>, then bytes will be written
 119      *                   to the end of the file rather than the beginning
 120      * @exception  FileNotFoundException  if the file exists but is a directory
 121      *                   rather than a regular file, does not exist but cannot
 122      *                   be created, or cannot be opened for any other reason.
 123      * @exception  SecurityException  if a security manager exists and its
 124      *               <code>checkWrite</code> method denies write access
 125      *               to the file.
 126      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 127      * @since     JDK1.1
 128      */
 129     public FileOutputStream(String name, boolean append)
 130         throws FileNotFoundException
 131     {
 132         this(name != null ? new File(name) : null, append);
 133     }
 134 
 135     /**
 136      * Creates a file output stream to write to the file represented by
 137      * the specified <code>File</code> object. A new
 138      * <code>FileDescriptor</code> object is created to represent this
 139      * file connection.
 140      * <p>
 141      * First, if there is a security manager, its <code>checkWrite</code>
 142      * method is called with the path represented by the <code>file</code>
 143      * argument as its argument.
 144      * <p>
 145      * If the file exists but is a directory rather than a regular file, does
 146      * not exist but cannot be created, or cannot be opened for any other
 147      * reason then a <code>FileNotFoundException</code> is thrown.
 148      *
 149      * @param      file               the file to be opened for writing.
 150      * @exception  FileNotFoundException  if the file exists but is a directory
 151      *                   rather than a regular file, does not exist but cannot
 152      *                   be created, or cannot be opened for any other reason
 153      * @exception  SecurityException  if a security manager exists and its
 154      *               <code>checkWrite</code> method denies write access
 155      *               to the file.
 156      * @see        java.io.File#getPath()
 157      * @see        java.lang.SecurityException
 158      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 159      */
 160     public FileOutputStream(File file) throws FileNotFoundException {
 161         this(file, false);
 162     }
 163 
 164     /**
 165      * Creates a file output stream to write to the file represented by
 166      * the specified <code>File</code> object. If the second argument is
 167      * <code>true</code>, then bytes will be written to the end of the file
 168      * rather than the beginning. A new <code>FileDescriptor</code> object is
 169      * created to represent this file connection.
 170      * <p>
 171      * First, if there is a security manager, its <code>checkWrite</code>
 172      * method is called with the path represented by the <code>file</code>
 173      * argument as its argument.
 174      * <p>
 175      * If the file exists but is a directory rather than a regular file, does
 176      * not exist but cannot be created, or cannot be opened for any other
 177      * reason then a <code>FileNotFoundException</code> is thrown.
 178      *
 179      * @param      file               the file to be opened for writing.
 180      * @param     append      if <code>true</code>, then bytes will be written
 181      *                   to the end of the file rather than the beginning
 182      * @exception  FileNotFoundException  if the file exists but is a directory
 183      *                   rather than a regular file, does not exist but cannot
 184      *                   be created, or cannot be opened for any other reason
 185      * @exception  SecurityException  if a security manager exists and its
 186      *               <code>checkWrite</code> method denies write access
 187      *               to the file.
 188      * @see        java.io.File#getPath()
 189      * @see        java.lang.SecurityException
 190      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 191      * @since 1.4
 192      */
 193     public FileOutputStream(File file, boolean append)
 194         throws FileNotFoundException
 195     {
 196         String name = (file != null ? file.getPath() : null);
 197         SecurityManager security = System.getSecurityManager();
 198         if (security != null) {
 199             security.checkWrite(name);
 200         }
 201         if (name == null) {
 202             throw new NullPointerException();
 203         }
 204         if (file.isInvalid()) {
 205             throw new FileNotFoundException("Invalid file path");
 206         }
 207         this.fd = new FileDescriptor();
 208         fd.attach(this);
 209         this.append = append;
 210         this.path = name;
 211 
 212         open(name, append);
 213     }
 214 
 215     /**
 216      * Creates a file output stream to write to the specified file
 217      * descriptor, which represents an existing connection to an actual
 218      * file in the file system.
 219      * <p>
 220      * First, if there is a security manager, its <code>checkWrite</code>
 221      * method is called with the file descriptor <code>fdObj</code>
 222      * argument as its argument.
 223      * <p>
 224      * If <code>fdObj</code> is null then a <code>NullPointerException</code>
 225      * is thrown.
 226      * <p>
 227      * This constructor does not throw an exception if <code>fdObj</code>
 228      * is {@link java.io.FileDescriptor#valid() invalid}.
 229      * However, if the methods are invoked on the resulting stream to attempt
 230      * I/O on the stream, an <code>IOException</code> is thrown.
 231      *
 232      * @param      fdObj   the file descriptor to be opened for writing
 233      * @exception  SecurityException  if a security manager exists and its
 234      *               <code>checkWrite</code> method denies
 235      *               write access to the file descriptor
 236      * @see        java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)
 237      */
 238     public FileOutputStream(FileDescriptor fdObj) {
 239         SecurityManager security = System.getSecurityManager();
 240         if (fdObj == null) {
 241             throw new NullPointerException();
 242         }
 243         if (security != null) {
 244             security.checkWrite(fdObj);
 245         }
 246         this.fd = fdObj;
 247         this.append = false;
 248         this.path = null;
 249 
 250         fd.attach(this);
 251     }
 252 
 253     /**
 254      * Opens a file, with the specified name, for overwriting or appending.
 255      * @param name name of file to be opened
 256      * @param append whether the file is to be opened in append mode
 257      */
 258     private native void open(String name, boolean append)
 259         throws FileNotFoundException;
 260 
 261     /**
 262      * Writes the specified byte to this file output stream.
 263      *
 264      * @param   b   the byte to be written.
 265      * @param   append   {@code true} if the write operation first
 266      *     advances the position to the end of file
 267      */
 268     private native void write(int b, boolean append) throws IOException;
 269 
 270     /**
 271      * Writes the specified byte to this file output stream. Implements
 272      * the <code>write</code> method of <code>OutputStream</code>.
 273      *
 274      * @param      b   the byte to be written.
 275      * @exception  IOException  if an I/O error occurs.
 276      */
 277     public void write(int b) throws IOException {
 278         write(b, append);
 279     }
 280 
 281     /**
 282      * Writes a sub array as a sequence of bytes.
 283      * @param b the data to be written
 284      * @param off the start offset in the data
 285      * @param len the number of bytes that are written
 286      * @param append {@code true} to first advance the position to the
 287      *     end of file
 288      * @exception IOException If an I/O error has occurred.
 289      */
 290     private native void writeBytes(byte b[], int off, int len, boolean append)
 291         throws IOException;
 292 
 293     /**
 294      * Writes <code>b.length</code> bytes from the specified byte array
 295      * to this file output stream.
 296      *
 297      * @param      b   the data.
 298      * @exception  IOException  if an I/O error occurs.
 299      */
 300     public void write(byte b[]) throws IOException {
 301         writeBytes(b, 0, b.length, append);
 302     }
 303 
 304     /**
 305      * Writes <code>len</code> bytes from the specified byte array
 306      * starting at offset <code>off</code> to this file output stream.
 307      *
 308      * @param      b     the data.
 309      * @param      off   the start offset in the data.
 310      * @param      len   the number of bytes to write.
 311      * @exception  IOException  if an I/O error occurs.
 312      */
 313     public void write(byte b[], int off, int len) throws IOException {
 314         writeBytes(b, off, len, append);
 315     }
 316 
 317     /**
 318      * Closes this file output stream and releases any system resources
 319      * associated with this stream. This file output stream may no longer
 320      * be used for writing bytes.
 321      *
 322      * <p> If this stream has an associated channel then the channel is closed
 323      * as well.
 324      *
 325      * @exception  IOException  if an I/O error occurs.
 326      *
 327      * @revised 1.4
 328      * @spec JSR-51
 329      */
 330     public void close() throws IOException {
 331         synchronized (closeLock) {
 332             if (closed) {
 333                 return;
 334             }
 335             closed = true;
 336         }
 337 
 338         if (channel != null) {
 339             channel.close();
 340         }
 341 
 342         fd.closeAll(new Closeable() {
 343             public void close() throws IOException {
 344                close0();
 345            }
 346         });
 347     }
 348 
 349     /**
 350      * Returns the file descriptor associated with this stream.
 351      *
 352      * @return  the <code>FileDescriptor</code> object that represents
 353      *          the connection to the file in the file system being used
 354      *          by this <code>FileOutputStream</code> object.
 355      *
 356      * @exception  IOException  if an I/O error occurs.
 357      * @see        java.io.FileDescriptor
 358      */
 359      public final FileDescriptor getFD()  throws IOException {
 360         if (fd != null) {
 361             return fd;
 362         }
 363         throw new IOException();
 364      }
 365 
 366     /**
 367      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
 368      * object associated with this file output stream.
 369      *
 370      * <p> The initial {@link java.nio.channels.FileChannel#position()
 371      * position} of the returned channel will be equal to the
 372      * number of bytes written to the file so far unless this stream is in
 373      * append mode, in which case it will be equal to the size of the file.
 374      * Writing bytes to this stream will increment the channel's position
 375      * accordingly.  Changing the channel's position, either explicitly or by
 376      * writing, will change this stream's file position.
 377      *
 378      * @return  the file channel associated with this file output stream
 379      *
 380      * @since 1.4
 381      * @spec JSR-51
 382      */
 383     public FileChannel getChannel() {
 384         synchronized (this) {
 385             if (channel == null) {
 386                 channel = FileChannelImpl.open(fd, path, false, true, append, this);
 387             }
 388             return channel;
 389         }
 390     }
 391 
 392     /**
 393      * Cleans up the connection to the file, and ensures that the
 394      * <code>close</code> method of this file output stream is
 395      * called when there are no more references to this stream.
 396      *
 397      * @exception  IOException  if an I/O error occurs.
 398      * @see        java.io.FileInputStream#close()
 399      */
 400     protected void finalize() throws IOException {
 401         if (fd != null) {
 402             if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
 403                 flush();
 404             } else {
 405                 /* if fd is shared, the references in FileDescriptor
 406                  * will ensure that finalizer is only called when
 407                  * safe to do so. All references using the fd have
 408                  * become unreachable. We can call close()
 409                  */
 410                 close();
 411             }
 412         }
 413     }
 414 
 415     private native void close0() throws IOException;
 416 
 417     private static native void initIDs();
 418 
 419     static {
 420         initIDs();
 421     }
 422 
 423 }