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