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