src/share/classes/java/io/FileOutputStream.java

Print this page
rev 6052 : [mq]: jdk.patch


  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     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>


 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         fd.attach(this);
 201         this.append = append;
 202 
 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 
 240         fd.attach(this);
 241     }
 242 
 243     /**
 244      * Opens a file, with the specified name, for overwriting or appending.
 245      * @param name name of file to be opened
 246      * @param append whether the file is to be opened in append mode
 247      */
 248     private native void open(String name, boolean append)
 249         throws FileNotFoundException;
 250 
 251     /**
 252      * Writes the specified byte to this file output stream.
 253      *
 254      * @param   b   the byte to be written.
 255      * @param   append   {@code true} if the write operation first
 256      *     advances the position to the end of file
 257      */
 258     private native void write(int b, boolean append) throws IOException;
 259 
 260     /**
 261      * Writes the specified byte to this file output stream. Implements
 262      * the <code>write</code> method of <code>OutputStream</code>.
 263      *
 264      * @param      b   the byte to be written.
 265      * @exception  IOException  if an I/O error occurs.
 266      */
 267     public void write(int b) throws IOException {

 268         write(b, append);

 269     }
 270 
 271     /**
 272      * Writes a sub array as a sequence of bytes.
 273      * @param b the data to be written
 274      * @param off the start offset in the data
 275      * @param len the number of bytes that are written
 276      * @param append {@code true} to first advance the position to the
 277      *     end of file
 278      * @exception IOException If an I/O error has occurred.
 279      */
 280     private native void writeBytes(byte b[], int off, int len, boolean append)
 281         throws IOException;
 282 
 283     /**
 284      * Writes <code>b.length</code> bytes from the specified byte array
 285      * to this file output stream.
 286      *
 287      * @param      b   the data.
 288      * @exception  IOException  if an I/O error occurs.
 289      */
 290     public void write(byte b[]) throws IOException {

 291         writeBytes(b, 0, b.length, append);

 292     }
 293 
 294     /**
 295      * Writes <code>len</code> bytes from the specified byte array
 296      * starting at offset <code>off</code> to this file output stream.
 297      *
 298      * @param      b     the data.
 299      * @param      off   the start offset in the data.
 300      * @param      len   the number of bytes to write.
 301      * @exception  IOException  if an I/O error occurs.
 302      */
 303     public void write(byte b[], int off, int len) throws IOException {

 304         writeBytes(b, off, len, append);

 305     }
 306 
 307     /**
 308      * Closes this file output stream and releases any system resources
 309      * associated with this stream. This file output stream may no longer
 310      * be used for writing bytes.
 311      *
 312      * <p> If this stream has an associated channel then the channel is closed
 313      * as well.
 314      *
 315      * @exception  IOException  if an I/O error occurs.
 316      *
 317      * @revised 1.4
 318      * @spec JSR-51
 319      */
 320     public void close() throws IOException {
 321         synchronized (closeLock) {
 322             if (closed) {
 323                 return;
 324             }


 356     /**
 357      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
 358      * object associated with this file output stream. </p>
 359      *
 360      * <p> The initial {@link java.nio.channels.FileChannel#position()
 361      * </code>position<code>} of the returned channel will be equal to the
 362      * number of bytes written to the file so far unless this stream is in
 363      * append mode, in which case it will be equal to the size of the file.
 364      * Writing bytes to this stream will increment the channel's position
 365      * accordingly.  Changing the channel's position, either explicitly or by
 366      * writing, will change this stream's file position.
 367      *
 368      * @return  the file channel associated with this file output stream
 369      *
 370      * @since 1.4
 371      * @spec JSR-51
 372      */
 373     public FileChannel getChannel() {
 374         synchronized (this) {
 375             if (channel == null) {
 376                 channel = FileChannelImpl.open(fd, false, true, append, this);
 377             }
 378             return channel;
 379         }
 380     }
 381 
 382     /**
 383      * Cleans up the connection to the file, and ensures that the
 384      * <code>close</code> method of this file output stream is
 385      * called when there are no more references to this stream.
 386      *
 387      * @exception  IOException  if an I/O error occurs.
 388      * @see        java.io.FileInputStream#close()
 389      */
 390     protected void finalize() throws IOException {
 391         if (fd != null) {
 392             if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
 393                 flush();
 394             } else {
 395                 /* if fd is shared, the references in FileDescriptor
 396                  * will ensure that finalizer is only called when


  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>


 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             }


 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