1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.io; 28 29 import static android.system.OsConstants.O_APPEND; 30 import static android.system.OsConstants.O_CREAT; 31 import static android.system.OsConstants.O_TRUNC; 32 import static android.system.OsConstants.O_WRONLY; 33 34 import java.nio.channels.FileChannel; 35 36 import dalvik.annotation.optimization.ReachabilitySensitive; 37 import dalvik.system.BlockGuard; 38 import dalvik.system.CloseGuard; 39 import sun.nio.ch.FileChannelImpl; 40 import libcore.io.IoBridge; 41 import libcore.io.IoTracker; 42 import libcore.io.IoUtils; 43 44 /** 45 * A file output stream is an output stream for writing data to a 46 * <code>File</code> or to a <code>FileDescriptor</code>. Whether or not 47 * a file is available or may be created depends upon the underlying 48 * platform. Some platforms, in particular, allow a file to be opened 49 * for writing by only one <tt>FileOutputStream</tt> (or other 50 * file-writing object) at a time. In such situations the constructors in 51 * this class will fail if the file involved is already open. 52 * 53 * <p><code>FileOutputStream</code> is meant for writing streams of raw bytes 54 * such as image data. For writing streams of characters, consider using 55 * <code>FileWriter</code>. 56 * 57 * @author Arthur van Hoff 58 * @see java.io.File 59 * @see java.io.FileDescriptor 60 * @see java.io.FileInputStream 61 * @see java.nio.file.Files#newOutputStream 62 * @since JDK1.0 63 */ 64 public 65 class FileOutputStream extends OutputStream 66 { 67 /** 68 * The system dependent file descriptor. 69 */ 70 // Android-added: @ReachabilitySensitive 71 @ReachabilitySensitive 72 private final FileDescriptor fd; 73 74 /** 75 * True if the file is opened for append. 76 */ 77 private final boolean append; 78 79 /** 80 * The associated channel, initialized lazily. 81 */ 82 private FileChannel channel; 83 84 /** 85 * The path of the referenced file 86 * (null if the stream is created with a file descriptor) 87 */ 88 private final String path; 89 90 private final Object closeLock = new Object(); 91 private volatile boolean closed = false; 92 93 // Android-added: CloseGuard support: Log if the stream is not closed. 94 @ReachabilitySensitive 95 private final CloseGuard guard = CloseGuard.get(); 96 97 // Android-added: Field for tracking whether the stream owns the underlying FileDescriptor. 98 private final boolean isFdOwner; 99 100 // Android-added: Tracking of unbuffered I/O. 101 private final IoTracker tracker = new IoTracker(); 102 103 /** 104 * Creates a file output stream to write to the file with the 105 * specified name. A new <code>FileDescriptor</code> object is 106 * created to represent this file connection. 107 * <p> 108 * First, if there is a security manager, its <code>checkWrite</code> 109 * method is called with <code>name</code> as its argument. 110 * <p> 111 * If the file exists but is a directory rather than a regular file, does 112 * not exist but cannot be created, or cannot be opened for any other 113 * reason then a <code>FileNotFoundException</code> is thrown. 114 * 115 * @param name the system-dependent filename 116 * @exception FileNotFoundException if the file exists but is a directory 117 * rather than a regular file, does not exist but cannot 118 * be created, or cannot be opened for any other reason 119 * @exception SecurityException if a security manager exists and its 120 * <code>checkWrite</code> method denies write access 121 * to the file. 122 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 123 */ FileOutputStream(String name)124 public FileOutputStream(String name) throws FileNotFoundException { 125 this(name != null ? new File(name) : null, false); 126 } 127 128 /** 129 * Creates a file output stream to write to the file with the specified 130 * name. If the second argument is <code>true</code>, then 131 * bytes will be written to the end of the file rather than the beginning. 132 * A new <code>FileDescriptor</code> object is created to represent this 133 * file connection. 134 * <p> 135 * First, if there is a security manager, its <code>checkWrite</code> 136 * method is called with <code>name</code> as its argument. 137 * <p> 138 * If the file exists but is a directory rather than a regular file, does 139 * not exist but cannot be created, or cannot be opened for any other 140 * reason then a <code>FileNotFoundException</code> is thrown. 141 * 142 * @param name the system-dependent file name 143 * @param append if <code>true</code>, then bytes will be written 144 * to the end of the file rather than the beginning 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.lang.SecurityManager#checkWrite(java.lang.String) 152 * @since JDK1.1 153 */ FileOutputStream(String name, boolean append)154 public FileOutputStream(String name, boolean append) 155 throws FileNotFoundException 156 { 157 this(name != null ? new File(name) : null, append); 158 } 159 160 /** 161 * Creates a file output stream to write to the file represented by 162 * the specified <code>File</code> object. A new 163 * <code>FileDescriptor</code> object is created to represent this 164 * 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 * @exception FileNotFoundException if the file exists but is a directory 176 * rather than a regular file, does not exist but cannot 177 * be created, or cannot be opened for any other reason 178 * @exception SecurityException if a security manager exists and its 179 * <code>checkWrite</code> method denies write access 180 * to the file. 181 * @see java.io.File#getPath() 182 * @see java.lang.SecurityException 183 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 184 */ FileOutputStream(File file)185 public FileOutputStream(File file) throws FileNotFoundException { 186 this(file, false); 187 } 188 189 /** 190 * Creates a file output stream to write to the file represented by 191 * the specified <code>File</code> object. If the second argument is 192 * <code>true</code>, then bytes will be written to the end of the file 193 * rather than the beginning. A new <code>FileDescriptor</code> object is 194 * created to represent this file connection. 195 * <p> 196 * First, if there is a security manager, its <code>checkWrite</code> 197 * method is called with the path represented by the <code>file</code> 198 * argument as its argument. 199 * <p> 200 * If the file exists but is a directory rather than a regular file, does 201 * not exist but cannot be created, or cannot be opened for any other 202 * reason then a <code>FileNotFoundException</code> is thrown. 203 * 204 * @param file the file to be opened for writing. 205 * @param append if <code>true</code>, then bytes will be written 206 * to the end of the file rather than the beginning 207 * @exception FileNotFoundException if the file exists but is a directory 208 * rather than a regular file, does not exist but cannot 209 * be created, or cannot be opened for any other reason 210 * @exception SecurityException if a security manager exists and its 211 * <code>checkWrite</code> method denies write access 212 * to the file. 213 * @see java.io.File#getPath() 214 * @see java.lang.SecurityException 215 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 216 * @since 1.4 217 */ FileOutputStream(File file, boolean append)218 public FileOutputStream(File file, boolean append) 219 throws FileNotFoundException 220 { 221 String name = (file != null ? file.getPath() : null); 222 SecurityManager security = System.getSecurityManager(); 223 if (security != null) { 224 security.checkWrite(name); 225 } 226 if (name == null) { 227 throw new NullPointerException(); 228 } 229 if (file.isInvalid()) { 230 throw new FileNotFoundException("Invalid file path"); 231 } 232 // BEGIN Android-changed: Open files using IoBridge to share BlockGuard & StrictMode logic. 233 // http://b/111268862 234 // this.fd = new FileDescriptor(); 235 int flags = O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC); 236 this.fd = IoBridge.open(name, flags); 237 // END Android-changed: Open files using IoBridge to share BlockGuard & StrictMode logic. 238 239 // Android-changed: Tracking mechanism for FileDescriptor sharing. 240 // fd.attach(this); 241 this.isFdOwner = true; 242 243 this.append = append; 244 this.path = name; 245 246 // Android-removed: Open files using IoBridge to share BlockGuard & StrictMode logic. 247 // open(name, append); 248 249 // Android-added: File descriptor ownership tracking. 250 IoUtils.setFdOwner(this.fd, this); 251 252 // Android-added: CloseGuard support. 253 guard.open("close"); 254 } 255 256 // Android-removed: Documentation around SecurityException. Not thrown on Android. 257 /** 258 * Creates a file output stream to write to the specified file 259 * descriptor, which represents an existing connection to an actual 260 * file in the file system. 261 * <p> 262 * First, if there is a security manager, its <code>checkWrite</code> 263 * method is called with the file descriptor <code>fdObj</code> 264 * argument as its argument. 265 * <p> 266 * If <code>fdObj</code> is null then a <code>NullPointerException</code> 267 * is thrown. 268 * <p> 269 * This constructor does not throw an exception if <code>fdObj</code> 270 * is {@link java.io.FileDescriptor#valid() invalid}. 271 * However, if the methods are invoked on the resulting stream to attempt 272 * I/O on the stream, an <code>IOException</code> is thrown. 273 * 274 * @param fdObj the file descriptor to be opened for writing 275 */ FileOutputStream(FileDescriptor fdObj)276 public FileOutputStream(FileDescriptor fdObj) { 277 // Android-changed: Delegate to added hidden constructor. 278 this(fdObj, false /* isOwner */); 279 } 280 281 // Android-added: Internal/hidden constructor for specifying FileDescriptor ownership. 282 // Android-removed: SecurityManager calls. 283 /** 284 * Internal constructor for {@code FileOutputStream} objects where the file descriptor 285 * is owned by this tream. 286 * 287 * @hide 288 */ FileOutputStream(FileDescriptor fdObj, boolean isFdOwner)289 public FileOutputStream(FileDescriptor fdObj, boolean isFdOwner) { 290 if (fdObj == null) { 291 // Android-changed: Improved NullPointerException message. 292 throw new NullPointerException("fdObj == null"); 293 } 294 295 this.fd = fdObj; 296 this.append = false; 297 this.path = null; 298 299 // Android-changed: FileDescriptor ownership tracking mechanism. 300 // fd.attach(this); 301 this.isFdOwner = isFdOwner; 302 if (isFdOwner) { 303 IoUtils.setFdOwner(this.fd, this); 304 } 305 } 306 307 // BEGIN Android-changed: Open files using IoBridge to share BlockGuard & StrictMode logic. 308 // http://b/112107427 309 /* 310 /** 311 * Opens a file, with the specified name, for overwriting or appending. 312 * @param name name of file to be opened 313 * @param append whether the file is to be opened in append mode 314 * 315 private native void open0(String name, boolean append) 316 throws FileNotFoundException; 317 318 // wrap native call to allow instrumentation 319 /** 320 * Opens a file, with the specified name, for overwriting or appending. 321 * @param name name of file to be opened 322 * @param append whether the file is to be opened in append mode 323 * 324 private void open(String name, boolean append) 325 throws FileNotFoundException { 326 open0(name, append); 327 } 328 */ 329 // END Android-changed: Open files using IoBridge to share BlockGuard & StrictMode logic. 330 331 // Android-removed: write(int, boolean), use IoBridge instead. 332 /* 333 /** 334 * Writes the specified byte to this file output stream. 335 * 336 * @param b the byte to be written. 337 * @param append {@code true} if the write operation first 338 * advances the position to the end of file 339 * 340 private native void write(int b, boolean append) throws IOException; 341 */ 342 343 /** 344 * Writes the specified byte to this file output stream. Implements 345 * the <code>write</code> method of <code>OutputStream</code>. 346 * 347 * @param b the byte to be written. 348 * @exception IOException if an I/O error occurs. 349 */ write(int b)350 public void write(int b) throws IOException { 351 // Android-changed: Write methods delegate to write(byte[],int,int) to share Android logic. 352 write(new byte[] { (byte) b }, 0, 1); 353 } 354 355 // Android-removed: Write methods delegate to write(byte[],int,int) to share Android logic. 356 /* 357 /** 358 * Writes a sub array as a sequence of bytes. 359 * @param b the data to be written 360 * @param off the start offset in the data 361 * @param len the number of bytes that are written 362 * @param append {@code true} to first advance the position to the 363 * end of file 364 * @exception IOException If an I/O error has occurred. 365 * 366 private native void writeBytes(byte b[], int off, int len, boolean append) 367 throws IOException; 368 */ 369 370 /** 371 * Writes <code>b.length</code> bytes from the specified byte array 372 * to this file output stream. 373 * 374 * @param b the data. 375 * @exception IOException if an I/O error occurs. 376 */ write(byte b[])377 public void write(byte b[]) throws IOException { 378 // Android-changed: Write methods delegate to write(byte[],int,int) to share Android logic. 379 write(b, 0, b.length); 380 } 381 382 /** 383 * Writes <code>len</code> bytes from the specified byte array 384 * starting at offset <code>off</code> to this file output stream. 385 * 386 * @param b the data. 387 * @param off the start offset in the data. 388 * @param len the number of bytes to write. 389 * @exception IOException if an I/O error occurs. 390 */ write(byte b[], int off, int len)391 public void write(byte b[], int off, int len) throws IOException { 392 // Android-added: close() check before I/O. 393 if (closed && len > 0) { 394 throw new IOException("Stream Closed"); 395 } 396 397 // Android-added: Tracking of unbuffered I/O. 398 tracker.trackIo(len, IoTracker.Mode.WRITE); 399 400 // Android-changed: Use IoBridge instead of calling native method. 401 IoBridge.write(fd, b, off, len); 402 } 403 404 /** 405 * Closes this file output stream and releases any system resources 406 * associated with this stream. This file output stream may no longer 407 * be used for writing bytes. 408 * 409 * <p> If this stream has an associated channel then the channel is closed 410 * as well. 411 * 412 * @exception IOException if an I/O error occurs. 413 * 414 * @revised 1.4 415 * @spec JSR-51 416 */ close()417 public void close() throws IOException { 418 synchronized (closeLock) { 419 if (closed) { 420 return; 421 } 422 closed = true; 423 } 424 425 // Android-added: CloseGuard support. 426 guard.close(); 427 428 if (channel != null) { 429 channel.close(); 430 } 431 432 // BEGIN Android-changed: Close handling / notification of blocked threads. 433 if (isFdOwner) { 434 IoBridge.closeAndSignalBlockedThreads(fd); 435 } 436 // END Android-changed: Close handling / notification of blocked threads. 437 } 438 439 /** 440 * Returns the file descriptor associated with this stream. 441 * 442 * @return the <code>FileDescriptor</code> object that represents 443 * the connection to the file in the file system being used 444 * by this <code>FileOutputStream</code> object. 445 * 446 * @exception IOException if an I/O error occurs. 447 * @see java.io.FileDescriptor 448 */ 449 // Android-added: @ReachabilitySensitive 450 @ReachabilitySensitive getFD()451 public final FileDescriptor getFD() throws IOException { 452 if (fd != null) { 453 return fd; 454 } 455 throw new IOException(); 456 } 457 458 /** 459 * Returns the unique {@link java.nio.channels.FileChannel FileChannel} 460 * object associated with this file output stream. 461 * 462 * <p> The initial {@link java.nio.channels.FileChannel#position() 463 * position} of the returned channel will be equal to the 464 * number of bytes written to the file so far unless this stream is in 465 * append mode, in which case it will be equal to the size of the file. 466 * Writing bytes to this stream will increment the channel's position 467 * accordingly. Changing the channel's position, either explicitly or by 468 * writing, will change this stream's file position. 469 * 470 * @return the file channel associated with this file output stream 471 * 472 * @since 1.4 473 * @spec JSR-51 474 */ getChannel()475 public FileChannel getChannel() { 476 synchronized (this) { 477 if (channel == null) { 478 channel = FileChannelImpl.open(fd, path, false, true, append, this); 479 } 480 return channel; 481 } 482 } 483 484 /** 485 * Cleans up the connection to the file, and ensures that the 486 * <code>close</code> method of this file output stream is 487 * called when there are no more references to this stream. 488 * 489 * @exception IOException if an I/O error occurs. 490 * @see java.io.FileInputStream#close() 491 */ finalize()492 protected void finalize() throws IOException { 493 // Android-added: CloseGuard support. 494 if (guard != null) { 495 guard.warnIfOpen(); 496 } 497 498 if (fd != null) { 499 if (fd == FileDescriptor.out || fd == FileDescriptor.err) { 500 flush(); 501 } else { 502 // Android-removed: Obsoleted comment about shared FileDescriptor handling. 503 close(); 504 } 505 } 506 } 507 508 // BEGIN Android-removed: Unused code. 509 /* 510 private native void close0() throws IOException; 511 512 private static native void initIDs(); 513 514 static { 515 initIDs(); 516 } 517 */ 518 // END Android-removed: Unused code. 519 520 } 521