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 dalvik.annotation.optimization.ReachabilitySensitive; 30 import java.nio.channels.FileChannel; 31 import sun.nio.ch.FileChannelImpl; 32 import android.system.Os; 33 import android.system.ErrnoException; 34 import dalvik.system.CloseGuard; 35 import libcore.io.IoBridge; 36 import libcore.io.IoTracker; 37 import libcore.io.IoUtils; 38 import libcore.io.Libcore; 39 import static android.system.OsConstants.*; 40 41 42 /** 43 * Instances of this class support both reading and writing to a 44 * random access file. A random access file behaves like a large 45 * array of bytes stored in the file system. There is a kind of cursor, 46 * or index into the implied array, called the <em>file pointer</em>; 47 * input operations read bytes starting at the file pointer and advance 48 * the file pointer past the bytes read. If the random access file is 49 * created in read/write mode, then output operations are also available; 50 * output operations write bytes starting at the file pointer and advance 51 * the file pointer past the bytes written. Output operations that write 52 * past the current end of the implied array cause the array to be 53 * extended. The file pointer can be read by the 54 * {@code getFilePointer} method and set by the {@code seek} 55 * method. 56 * <p> 57 * It is generally true of all the reading routines in this class that 58 * if end-of-file is reached before the desired number of bytes has been 59 * read, an {@code EOFException} (which is a kind of 60 * {@code IOException}) is thrown. If any byte cannot be read for 61 * any reason other than end-of-file, an {@code IOException} other 62 * than {@code EOFException} is thrown. In particular, an 63 * {@code IOException} may be thrown if the stream has been closed. 64 * 65 * @author unascribed 66 * @since JDK1.0 67 */ 68 69 public class RandomAccessFile implements DataOutput, DataInput, Closeable { 70 71 // BEGIN Android-added: CloseGuard and some helper fields for Android changes in this file. 72 @ReachabilitySensitive 73 private final CloseGuard guard = CloseGuard.get(); 74 private final byte[] scratch = new byte[8]; 75 76 private static final int FLUSH_NONE = 0; 77 private static final int FLUSH_FSYNC = 1; 78 private static final int FLUSH_FDATASYNC = 2; 79 private int flushAfterWrite = FLUSH_NONE; 80 81 private int mode; 82 // END Android-added: CloseGuard and some helper fields for Android changes in this file. 83 84 // Android-added: @ReachabilitySensitive 85 @ReachabilitySensitive 86 private FileDescriptor fd; 87 private FileChannel channel = null; 88 private boolean rw; 89 90 /** 91 * The path of the referenced file 92 * (null if the stream is created with a file descriptor) 93 */ 94 private final String path; 95 96 private Object closeLock = new Object(); 97 private volatile boolean closed = false; 98 99 // BEGIN Android-added: IoTracker. 100 /** 101 * A single tracker to track both read and write. The tracker resets when the operation 102 * performed is different from the operation last performed. 103 */ 104 private final IoTracker ioTracker = new IoTracker(); 105 // END Android-added: IoTracker. 106 107 /** 108 * Creates a random access file stream to read from, and optionally 109 * to write to, a file with the specified name. A new 110 * {@link FileDescriptor} object is created to represent the 111 * connection to the file. 112 * 113 * <p> The <tt>mode</tt> argument specifies the access mode with which the 114 * file is to be opened. The permitted values and their meanings are as 115 * specified for the <a 116 * href="#mode"><tt>RandomAccessFile(File,String)</tt></a> constructor. 117 * 118 * <p> 119 * If there is a security manager, its {@code checkRead} method 120 * is called with the {@code name} argument 121 * as its argument to see if read access to the file is allowed. 122 * If the mode allows writing, the security manager's 123 * {@code checkWrite} method 124 * is also called with the {@code name} argument 125 * as its argument to see if write access to the file is allowed. 126 * 127 * @param name the system-dependent filename 128 * @param mode the access <a href="#mode">mode</a> 129 * @exception IllegalArgumentException if the mode argument is not equal 130 * to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or 131 * <tt>"rwd"</tt> 132 * @exception FileNotFoundException 133 * if the mode is <tt>"r"</tt> but the given string does not 134 * denote an existing regular file, or if the mode begins with 135 * <tt>"rw"</tt> but the given string does not denote an 136 * existing, writable regular file and a new regular file of 137 * that name cannot be created, or if some other error occurs 138 * while opening or creating the file 139 * @exception SecurityException if a security manager exists and its 140 * {@code checkRead} method denies read access to the file 141 * or the mode is "rw" and the security manager's 142 * {@code checkWrite} method denies write access to the file 143 * @see java.lang.SecurityException 144 * @see java.lang.SecurityManager#checkRead(java.lang.String) 145 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 146 * @revised 1.4 147 * @spec JSR-51 148 */ RandomAccessFile(String name, String mode)149 public RandomAccessFile(String name, String mode) 150 throws FileNotFoundException 151 { 152 this(name != null ? new File(name) : null, mode); 153 } 154 155 /** 156 * Creates a random access file stream to read from, and optionally to 157 * write to, the file specified by the {@link File} argument. A new {@link 158 * FileDescriptor} object is created to represent this file connection. 159 * 160 * <p>The <a name="mode"><tt>mode</tt></a> argument specifies the access mode 161 * in which the file is to be opened. The permitted values and their 162 * meanings are: 163 * 164 * <table summary="Access mode permitted values and meanings"> 165 * <tr><th align="left">Value</th><th align="left">Meaning</th></tr> 166 * <tr><td valign="top"><tt>"r"</tt></td> 167 * <td> Open for reading only. Invoking any of the <tt>write</tt> 168 * methods of the resulting object will cause an {@link 169 * java.io.IOException} to be thrown. </td></tr> 170 * <tr><td valign="top"><tt>"rw"</tt></td> 171 * <td> Open for reading and writing. If the file does not already 172 * exist then an attempt will be made to create it. </td></tr> 173 * <tr><td valign="top"><tt>"rws"</tt></td> 174 * <td> Open for reading and writing, as with <tt>"rw"</tt>, and also 175 * require that every update to the file's content or metadata be 176 * written synchronously to the underlying storage device. </td></tr> 177 * <tr><td valign="top"><tt>"rwd" </tt></td> 178 * <td> Open for reading and writing, as with <tt>"rw"</tt>, and also 179 * require that every update to the file's content be written 180 * synchronously to the underlying storage device. </td></tr> 181 * </table> 182 * 183 * The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link 184 * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of 185 * the {@link java.nio.channels.FileChannel} class, passing arguments of 186 * <tt>true</tt> and <tt>false</tt>, respectively, except that they always 187 * apply to every I/O operation and are therefore often more efficient. If 188 * the file resides on a local storage device then when an invocation of a 189 * method of this class returns it is guaranteed that all changes made to 190 * the file by that invocation will have been written to that device. This 191 * is useful for ensuring that critical information is not lost in the 192 * event of a system crash. If the file does not reside on a local device 193 * then no such guarantee is made. 194 * 195 * <p>The <tt>"rwd"</tt> mode can be used to reduce the number of I/O 196 * operations performed. Using <tt>"rwd"</tt> only requires updates to the 197 * file's content to be written to storage; using <tt>"rws"</tt> requires 198 * updates to both the file's content and its metadata to be written, which 199 * generally requires at least one more low-level I/O operation. 200 * 201 * <p>If there is a security manager, its {@code checkRead} method is 202 * called with the pathname of the {@code file} argument as its 203 * argument to see if read access to the file is allowed. If the mode 204 * allows writing, the security manager's {@code checkWrite} method is 205 * also called with the path argument to see if write access to the file is 206 * allowed. 207 * 208 * @param file the file object 209 * @param mode the access mode, as described 210 * <a href="#mode">above</a> 211 * @exception IllegalArgumentException if the mode argument is not equal 212 * to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or 213 * <tt>"rwd"</tt> 214 * @exception FileNotFoundException 215 * if the mode is <tt>"r"</tt> but the given file object does 216 * not denote an existing regular file, or if the mode begins 217 * with <tt>"rw"</tt> but the given file object does not denote 218 * an existing, writable regular file and a new regular file of 219 * that name cannot be created, or if some other error occurs 220 * while opening or creating the file 221 * @exception SecurityException if a security manager exists and its 222 * {@code checkRead} method denies read access to the file 223 * or the mode is "rw" and the security manager's 224 * {@code checkWrite} method denies write access to the file 225 * @see java.lang.SecurityManager#checkRead(java.lang.String) 226 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 227 * @see java.nio.channels.FileChannel#force(boolean) 228 * @revised 1.4 229 * @spec JSR-51 230 */ RandomAccessFile(File file, String mode)231 public RandomAccessFile(File file, String mode) 232 throws FileNotFoundException 233 { 234 String name = (file != null ? file.getPath() : null); 235 int imode = -1; 236 if (mode.equals("r")) { 237 imode = O_RDONLY; 238 } else if (mode.startsWith("rw")) { 239 // Android-changed: Added. O_CREAT 240 // imode = O_RDWR; 241 imode = O_RDWR | O_CREAT; 242 rw = true; 243 if (mode.length() > 2) { 244 if (mode.equals("rws")) { 245 // Android-changed: For performance reasons, use fsync after each write. 246 // RandomAccessFile.write may result in multiple write syscalls, 247 // O_SYNC/O_DSYNC flags will cause a blocking wait on each syscall. Replacing 248 // them with single fsync/fdatasync call gives better performance with only 249 // minor decrease in reliability. 250 // imode |= O_SYNC; 251 flushAfterWrite = FLUSH_FSYNC; 252 } else if (mode.equals("rwd")) { 253 // Android-changed: For performance reasons, use fdatasync after each write. 254 // imode |= O_DSYNC; 255 flushAfterWrite = FLUSH_FDATASYNC; 256 } else { 257 imode = -1; 258 } 259 } 260 } 261 if (imode < 0) { 262 throw new IllegalArgumentException("Illegal mode \"" + mode 263 + "\" must be one of " 264 + "\"r\", \"rw\", \"rws\"," 265 + " or \"rwd\""); 266 } 267 // Android-removed: do not use legacy security code 268 /* 269 SecurityManager security = System.getSecurityManager(); 270 if (security != null) { 271 security.checkRead(name); 272 if (rw) { 273 security.checkWrite(name); 274 } 275 } 276 */ 277 if (name == null) { 278 // Android-changed: different exception message in ctor when file == null. 279 // throw new NullPointerException(); 280 throw new NullPointerException("file == null"); 281 } 282 if (file.isInvalid()) { 283 throw new FileNotFoundException("Invalid file path"); 284 } 285 this.path = name; 286 this.mode = imode; 287 288 // BEGIN Android-changed: Use IoBridge.open() instead of open. 289 fd = IoBridge.open(name, imode); 290 IoUtils.setFdOwner(fd, this); 291 maybeSync(); 292 guard.open("close"); 293 // END Android-changed: Use IoBridge.open() instead of open. 294 } 295 296 // BEGIN Android-added: Sync after rws/rwd write maybeSync()297 private void maybeSync() { 298 if (flushAfterWrite == FLUSH_FSYNC) { 299 try { 300 fd.sync(); 301 } catch (IOException e) { 302 // Ignored 303 } 304 } else if (flushAfterWrite == FLUSH_FDATASYNC) { 305 try { 306 Os.fdatasync(fd); 307 } catch (ErrnoException e) { 308 // Ignored 309 } 310 } 311 } 312 // END Android-added: Sync after rws/rwd write 313 314 /** 315 * Returns the opaque file descriptor object associated with this 316 * stream. 317 * 318 * @return the file descriptor object associated with this stream. 319 * @exception IOException if an I/O error occurs. 320 * @see java.io.FileDescriptor 321 */ getFD()322 public final FileDescriptor getFD() throws IOException { 323 if (fd != null) { 324 return fd; 325 } 326 throw new IOException(); 327 } 328 329 /** 330 * Returns the unique {@link java.nio.channels.FileChannel FileChannel} 331 * object associated with this file. 332 * 333 * <p> The {@link java.nio.channels.FileChannel#position() 334 * position} of the returned channel will always be equal to 335 * this object's file-pointer offset as returned by the {@link 336 * #getFilePointer getFilePointer} method. Changing this object's 337 * file-pointer offset, whether explicitly or by reading or writing bytes, 338 * will change the position of the channel, and vice versa. Changing the 339 * file's length via this object will change the length seen via the file 340 * channel, and vice versa. 341 * 342 * @return the file channel associated with this file 343 * 344 * @since 1.4 345 * @spec JSR-51 346 */ getChannel()347 public final FileChannel getChannel() { 348 synchronized (this) { 349 if (channel == null) { 350 channel = FileChannelImpl.open(fd, path, true, rw, this); 351 } 352 return channel; 353 } 354 } 355 356 /** 357 * Reads a byte of data from this file. The byte is returned as an 358 * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This 359 * method blocks if no input is yet available. 360 * <p> 361 * Although {@code RandomAccessFile} is not a subclass of 362 * {@code InputStream}, this method behaves in exactly the same 363 * way as the {@link InputStream#read()} method of 364 * {@code InputStream}. 365 * 366 * @return the next byte of data, or {@code -1} if the end of the 367 * file has been reached. 368 * @exception IOException if an I/O error occurs. Not thrown if 369 * end-of-file has been reached. 370 */ read()371 public int read() throws IOException { 372 // Android-changed: Implement on top of libcore os API. 373 // return read0(); 374 return (read(scratch, 0, 1) != -1) ? scratch[0] & 0xff : -1; 375 } 376 377 /** 378 * Reads a sub array as a sequence of bytes. 379 * @param b the buffer into which the data is read. 380 * @param off the start offset of the data. 381 * @param len the number of bytes to read. 382 * @exception IOException If an I/O error has occurred. 383 */ readBytes(byte b[], int off, int len)384 private int readBytes(byte b[], int off, int len) throws IOException { 385 // Android-changed: Implement on top of libcore os API. 386 ioTracker.trackIo(len, IoTracker.Mode.READ); 387 return IoBridge.read(fd, b, off, len); 388 } 389 390 /** 391 * Reads up to {@code len} bytes of data from this file into an 392 * array of bytes. This method blocks until at least one byte of input 393 * is available. 394 * <p> 395 * Although {@code RandomAccessFile} is not a subclass of 396 * {@code InputStream}, this method behaves in exactly the 397 * same way as the {@link InputStream#read(byte[], int, int)} method of 398 * {@code InputStream}. 399 * 400 * @param b the buffer into which the data is read. 401 * @param off the start offset in array {@code b} 402 * at which the data is written. 403 * @param len the maximum number of bytes read. 404 * @return the total number of bytes read into the buffer, or 405 * {@code -1} if there is no more data because the end of 406 * the file has been reached. 407 * @exception IOException If the first byte cannot be read for any reason 408 * other than end of file, or if the random access file has been closed, or if 409 * some other I/O error occurs. 410 * @exception NullPointerException If {@code b} is {@code null}. 411 * @exception IndexOutOfBoundsException If {@code off} is negative, 412 * {@code len} is negative, or {@code len} is greater than 413 * {@code b.length - off} 414 */ read(byte b[], int off, int len)415 public int read(byte b[], int off, int len) throws IOException { 416 return readBytes(b, off, len); 417 } 418 419 /** 420 * Reads up to {@code b.length} bytes of data from this file 421 * into an array of bytes. This method blocks until at least one byte 422 * of input is available. 423 * <p> 424 * Although {@code RandomAccessFile} is not a subclass of 425 * {@code InputStream}, this method behaves in exactly the 426 * same way as the {@link InputStream#read(byte[])} method of 427 * {@code InputStream}. 428 * 429 * @param b the buffer into which the data is read. 430 * @return the total number of bytes read into the buffer, or 431 * {@code -1} if there is no more data because the end of 432 * this file has been reached. 433 * @exception IOException If the first byte cannot be read for any reason 434 * other than end of file, or if the random access file has been closed, or if 435 * some other I/O error occurs. 436 * @exception NullPointerException If {@code b} is {@code null}. 437 */ read(byte b[])438 public int read(byte b[]) throws IOException { 439 return readBytes(b, 0, b.length); 440 } 441 442 /** 443 * Reads {@code b.length} bytes from this file into the byte 444 * array, starting at the current file pointer. This method reads 445 * repeatedly from the file until the requested number of bytes are 446 * read. This method blocks until the requested number of bytes are 447 * read, the end of the stream is detected, or an exception is thrown. 448 * 449 * @param b the buffer into which the data is read. 450 * @exception EOFException if this file reaches the end before reading 451 * all the bytes. 452 * @exception IOException if an I/O error occurs. 453 */ readFully(byte b[])454 public final void readFully(byte b[]) throws IOException { 455 readFully(b, 0, b.length); 456 } 457 458 /** 459 * Reads exactly {@code len} bytes from this file into the byte 460 * array, starting at the current file pointer. This method reads 461 * repeatedly from the file until the requested number of bytes are 462 * read. This method blocks until the requested number of bytes are 463 * read, the end of the stream is detected, or an exception is thrown. 464 * 465 * @param b the buffer into which the data is read. 466 * @param off the start offset of the data. 467 * @param len the number of bytes to read. 468 * @exception EOFException if this file reaches the end before reading 469 * all the bytes. 470 * @exception IOException if an I/O error occurs. 471 */ readFully(byte b[], int off, int len)472 public final void readFully(byte b[], int off, int len) throws IOException { 473 int n = 0; 474 do { 475 int count = this.read(b, off + n, len - n); 476 if (count < 0) 477 throw new EOFException(); 478 n += count; 479 } while (n < len); 480 } 481 482 /** 483 * Attempts to skip over {@code n} bytes of input discarding the 484 * skipped bytes. 485 * <p> 486 * 487 * This method may skip over some smaller number of bytes, possibly zero. 488 * This may result from any of a number of conditions; reaching end of 489 * file before {@code n} bytes have been skipped is only one 490 * possibility. This method never throws an {@code EOFException}. 491 * The actual number of bytes skipped is returned. If {@code n} 492 * is negative, no bytes are skipped. 493 * 494 * @param n the number of bytes to be skipped. 495 * @return the actual number of bytes skipped. 496 * @exception IOException if an I/O error occurs. 497 */ skipBytes(int n)498 public int skipBytes(int n) throws IOException { 499 long pos; 500 long len; 501 long newpos; 502 503 if (n <= 0) { 504 return 0; 505 } 506 pos = getFilePointer(); 507 len = length(); 508 newpos = pos + n; 509 if (newpos > len) { 510 newpos = len; 511 } 512 seek(newpos); 513 514 /* return the actual number of bytes skipped */ 515 return (int) (newpos - pos); 516 } 517 518 // 'Write' primitives 519 520 /** 521 * Writes the specified byte to this file. The write starts at 522 * the current file pointer. 523 * 524 * @param b the {@code byte} to be written. 525 * @exception IOException if an I/O error occurs. 526 */ write(int b)527 public void write(int b) throws IOException { 528 // BEGIN Android-changed: Implement on top of libcore os API. 529 // write0(b); 530 scratch[0] = (byte) (b & 0xff); 531 write(scratch, 0, 1); 532 // END Android-changed: Implement on top of libcore os API. 533 } 534 535 /** 536 * Writes a sub array as a sequence of bytes. 537 * @param b the data to be written 538 539 * @param off the start offset in the data 540 * @param len the number of bytes that are written 541 * @exception IOException If an I/O error has occurred. 542 */ writeBytes(byte b[], int off, int len)543 private void writeBytes(byte b[], int off, int len) throws IOException { 544 // BEGIN Android-changed: Implement on top of libcore os API. 545 ioTracker.trackIo(len, IoTracker.Mode.WRITE); 546 IoBridge.write(fd, b, off, len); 547 maybeSync(); 548 // END Android-changed: Implement on top of libcore os API. 549 } 550 551 /** 552 * Writes {@code b.length} bytes from the specified byte array 553 * to this file, starting at the current file pointer. 554 * 555 * @param b the data. 556 * @exception IOException if an I/O error occurs. 557 */ write(byte b[])558 public void write(byte b[]) throws IOException { 559 writeBytes(b, 0, b.length); 560 } 561 562 /** 563 * Writes {@code len} bytes from the specified byte array 564 * starting at offset {@code off} to this file. 565 * 566 * @param b the data. 567 * @param off the start offset in the data. 568 * @param len the number of bytes to write. 569 * @exception IOException if an I/O error occurs. 570 */ write(byte b[], int off, int len)571 public void write(byte b[], int off, int len) throws IOException { 572 writeBytes(b, off, len); 573 } 574 575 // 'Random access' stuff 576 577 /** 578 * Returns the current offset in this file. 579 * 580 * @return the offset from the beginning of the file, in bytes, 581 * at which the next read or write occurs. 582 * @exception IOException if an I/O error occurs. 583 */ getFilePointer()584 public long getFilePointer() throws IOException { 585 // BEGIN Android-changed: Implement on top of libcore os API. 586 try { 587 return Libcore.os.lseek(fd, 0L, SEEK_CUR); 588 } catch (ErrnoException errnoException) { 589 throw errnoException.rethrowAsIOException(); 590 } 591 // END Android-changed: Implement on top of libcore os API. 592 } 593 594 /** 595 * Sets the file-pointer offset, measured from the beginning of this 596 * file, at which the next read or write occurs. The offset may be 597 * set beyond the end of the file. Setting the offset beyond the end 598 * of the file does not change the file length. The file length will 599 * change only by writing after the offset has been set beyond the end 600 * of the file. 601 * 602 * @param pos the offset position, measured in bytes from the 603 * beginning of the file, at which to set the file 604 * pointer. 605 * @exception IOException if {@code pos} is less than 606 * {@code 0} or if an I/O error occurs. 607 */ seek(long pos)608 public void seek(long pos) throws IOException { 609 if (pos < 0) { 610 // Android-changed: different exception message for seek(-1). 611 // throw new IOException("Negative seek offset"); 612 throw new IOException("offset < 0: " + pos); 613 } else { 614 // BEGIN Android-changed: Implement on top of libcore os API. 615 // seek0(pos); 616 try { 617 Libcore.os.lseek(fd, pos, SEEK_SET); 618 ioTracker.reset(); 619 } catch (ErrnoException errnoException) { 620 throw errnoException.rethrowAsIOException(); 621 } 622 // END Android-changed: Implement on top of libcore os API. 623 } 624 } 625 626 /** 627 * Returns the length of this file. 628 * 629 * @return the length of this file, measured in bytes. 630 * @exception IOException if an I/O error occurs. 631 */ length()632 public long length() throws IOException { 633 // BEGIN Android-changed: Implement on top of libcore os API. 634 try { 635 return Libcore.os.fstat(fd).st_size; 636 } catch (ErrnoException errnoException) { 637 throw errnoException.rethrowAsIOException(); 638 } 639 // END Android-changed: Implement on top of libcore os API. 640 } 641 642 /** 643 * Sets the length of this file. 644 * 645 * <p> If the present length of the file as returned by the 646 * {@code length} method is greater than the {@code newLength} 647 * argument then the file will be truncated. In this case, if the file 648 * offset as returned by the {@code getFilePointer} method is greater 649 * than {@code newLength} then after this method returns the offset 650 * will be equal to {@code newLength}. 651 * 652 * <p> If the present length of the file as returned by the 653 * {@code length} method is smaller than the {@code newLength} 654 * argument then the file will be extended. In this case, the contents of 655 * the extended portion of the file are not defined. 656 * 657 * @param newLength The desired length of the file 658 * @exception IOException If an I/O error occurs 659 * @since 1.2 660 */ setLength(long newLength)661 public void setLength(long newLength) throws IOException { 662 // BEGIN Android-changed: Implement on top of libcore os API. 663 if (newLength < 0) { 664 throw new IllegalArgumentException("newLength < 0"); 665 } 666 try { 667 Libcore.os.ftruncate(fd, newLength); 668 } catch (ErrnoException errnoException) { 669 throw errnoException.rethrowAsIOException(); 670 } 671 672 long filePointer = getFilePointer(); 673 if (filePointer > newLength) { 674 seek(newLength); 675 } 676 maybeSync(); 677 // END Android-changed: Implement on top of libcore os API. 678 } 679 680 681 /** 682 * Closes this random access file stream and releases any system 683 * resources associated with the stream. A closed random access 684 * file cannot perform input or output operations and cannot be 685 * reopened. 686 * 687 * <p> If this file has an associated channel then the channel is closed 688 * as well. 689 * 690 * @exception IOException if an I/O error occurs. 691 * 692 * @revised 1.4 693 * @spec JSR-51 694 */ close()695 public void close() throws IOException { 696 guard.close(); 697 synchronized (closeLock) { 698 if (closed) { 699 return; 700 } 701 closed = true; 702 } 703 704 // BEGIN Android-changed: Implement on top of libcore os API. 705 if (channel != null && channel.isOpen()) { 706 channel.close(); 707 } 708 IoBridge.closeAndSignalBlockedThreads(fd); 709 // END Android-changed: Implement on top of libcore os API. 710 } 711 712 // 713 // Some "reading/writing Java data types" methods stolen from 714 // DataInputStream and DataOutputStream. 715 // 716 717 /** 718 * Reads a {@code boolean} from this file. This method reads a 719 * single byte from the file, starting at the current file pointer. 720 * A value of {@code 0} represents 721 * {@code false}. Any other value represents {@code true}. 722 * This method blocks until the byte is read, the end of the stream 723 * is detected, or an exception is thrown. 724 * 725 * @return the {@code boolean} value read. 726 * @exception EOFException if this file has reached the end. 727 * @exception IOException if an I/O error occurs. 728 */ readBoolean()729 public final boolean readBoolean() throws IOException { 730 int ch = this.read(); 731 if (ch < 0) 732 throw new EOFException(); 733 return (ch != 0); 734 } 735 736 /** 737 * Reads a signed eight-bit value from this file. This method reads a 738 * byte from the file, starting from the current file pointer. 739 * If the byte read is {@code b}, where 740 * <code>0 <= b <= 255</code>, 741 * then the result is: 742 * <blockquote><pre> 743 * (byte)(b) 744 * </pre></blockquote> 745 * <p> 746 * This method blocks until the byte is read, the end of the stream 747 * is detected, or an exception is thrown. 748 * 749 * @return the next byte of this file as a signed eight-bit 750 * {@code byte}. 751 * @exception EOFException if this file has reached the end. 752 * @exception IOException if an I/O error occurs. 753 */ readByte()754 public final byte readByte() throws IOException { 755 int ch = this.read(); 756 if (ch < 0) 757 throw new EOFException(); 758 return (byte)(ch); 759 } 760 761 /** 762 * Reads an unsigned eight-bit number from this file. This method reads 763 * a byte from this file, starting at the current file pointer, 764 * and returns that byte. 765 * <p> 766 * This method blocks until the byte is read, the end of the stream 767 * is detected, or an exception is thrown. 768 * 769 * @return the next byte of this file, interpreted as an unsigned 770 * eight-bit number. 771 * @exception EOFException if this file has reached the end. 772 * @exception IOException if an I/O error occurs. 773 */ readUnsignedByte()774 public final int readUnsignedByte() throws IOException { 775 int ch = this.read(); 776 if (ch < 0) 777 throw new EOFException(); 778 return ch; 779 } 780 781 /** 782 * Reads a signed 16-bit number from this file. The method reads two 783 * bytes from this file, starting at the current file pointer. 784 * If the two bytes read, in order, are 785 * {@code b1} and {@code b2}, where each of the two values is 786 * between {@code 0} and {@code 255}, inclusive, then the 787 * result is equal to: 788 * <blockquote><pre> 789 * (short)((b1 << 8) | b2) 790 * </pre></blockquote> 791 * <p> 792 * This method blocks until the two bytes are read, the end of the 793 * stream is detected, or an exception is thrown. 794 * 795 * @return the next two bytes of this file, interpreted as a signed 796 * 16-bit number. 797 * @exception EOFException if this file reaches the end before reading 798 * two bytes. 799 * @exception IOException if an I/O error occurs. 800 */ readShort()801 public final short readShort() throws IOException { 802 int ch1 = this.read(); 803 int ch2 = this.read(); 804 if ((ch1 | ch2) < 0) 805 throw new EOFException(); 806 return (short)((ch1 << 8) + (ch2 << 0)); 807 } 808 809 /** 810 * Reads an unsigned 16-bit number from this file. This method reads 811 * two bytes from the file, starting at the current file pointer. 812 * If the bytes read, in order, are 813 * {@code b1} and {@code b2}, where 814 * <code>0 <= b1, b2 <= 255</code>, 815 * then the result is equal to: 816 * <blockquote><pre> 817 * (b1 << 8) | b2 818 * </pre></blockquote> 819 * <p> 820 * This method blocks until the two bytes are read, the end of the 821 * stream is detected, or an exception is thrown. 822 * 823 * @return the next two bytes of this file, interpreted as an unsigned 824 * 16-bit integer. 825 * @exception EOFException if this file reaches the end before reading 826 * two bytes. 827 * @exception IOException if an I/O error occurs. 828 */ readUnsignedShort()829 public final int readUnsignedShort() throws IOException { 830 int ch1 = this.read(); 831 int ch2 = this.read(); 832 if ((ch1 | ch2) < 0) 833 throw new EOFException(); 834 return (ch1 << 8) + (ch2 << 0); 835 } 836 837 /** 838 * Reads a character from this file. This method reads two 839 * bytes from the file, starting at the current file pointer. 840 * If the bytes read, in order, are 841 * {@code b1} and {@code b2}, where 842 * <code>0 <= b1, b2 <= 255</code>, 843 * then the result is equal to: 844 * <blockquote><pre> 845 * (char)((b1 << 8) | b2) 846 * </pre></blockquote> 847 * <p> 848 * This method blocks until the two bytes are read, the end of the 849 * stream is detected, or an exception is thrown. 850 * 851 * @return the next two bytes of this file, interpreted as a 852 * {@code char}. 853 * @exception EOFException if this file reaches the end before reading 854 * two bytes. 855 * @exception IOException if an I/O error occurs. 856 */ readChar()857 public final char readChar() throws IOException { 858 int ch1 = this.read(); 859 int ch2 = this.read(); 860 if ((ch1 | ch2) < 0) 861 throw new EOFException(); 862 return (char)((ch1 << 8) + (ch2 << 0)); 863 } 864 865 /** 866 * Reads a signed 32-bit integer from this file. This method reads 4 867 * bytes from the file, starting at the current file pointer. 868 * If the bytes read, in order, are {@code b1}, 869 * {@code b2}, {@code b3}, and {@code b4}, where 870 * <code>0 <= b1, b2, b3, b4 <= 255</code>, 871 * then the result is equal to: 872 * <blockquote><pre> 873 * (b1 << 24) | (b2 << 16) + (b3 << 8) + b4 874 * </pre></blockquote> 875 * <p> 876 * This method blocks until the four bytes are read, the end of the 877 * stream is detected, or an exception is thrown. 878 * 879 * @return the next four bytes of this file, interpreted as an 880 * {@code int}. 881 * @exception EOFException if this file reaches the end before reading 882 * four bytes. 883 * @exception IOException if an I/O error occurs. 884 */ readInt()885 public final int readInt() throws IOException { 886 int ch1 = this.read(); 887 int ch2 = this.read(); 888 int ch3 = this.read(); 889 int ch4 = this.read(); 890 if ((ch1 | ch2 | ch3 | ch4) < 0) 891 throw new EOFException(); 892 return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); 893 } 894 895 /** 896 * Reads a signed 64-bit integer from this file. This method reads eight 897 * bytes from the file, starting at the current file pointer. 898 * If the bytes read, in order, are 899 * {@code b1}, {@code b2}, {@code b3}, 900 * {@code b4}, {@code b5}, {@code b6}, 901 * {@code b7}, and {@code b8,} where: 902 * <blockquote><pre> 903 * 0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255, 904 * </pre></blockquote> 905 * <p> 906 * then the result is equal to: 907 * <blockquote><pre> 908 * ((long)b1 << 56) + ((long)b2 << 48) 909 * + ((long)b3 << 40) + ((long)b4 << 32) 910 * + ((long)b5 << 24) + ((long)b6 << 16) 911 * + ((long)b7 << 8) + b8 912 * </pre></blockquote> 913 * <p> 914 * This method blocks until the eight bytes are read, the end of the 915 * stream is detected, or an exception is thrown. 916 * 917 * @return the next eight bytes of this file, interpreted as a 918 * {@code long}. 919 * @exception EOFException if this file reaches the end before reading 920 * eight bytes. 921 * @exception IOException if an I/O error occurs. 922 */ readLong()923 public final long readLong() throws IOException { 924 return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL); 925 } 926 927 /** 928 * Reads a {@code float} from this file. This method reads an 929 * {@code int} value, starting at the current file pointer, 930 * as if by the {@code readInt} method 931 * and then converts that {@code int} to a {@code float} 932 * using the {@code intBitsToFloat} method in class 933 * {@code Float}. 934 * <p> 935 * This method blocks until the four bytes are read, the end of the 936 * stream is detected, or an exception is thrown. 937 * 938 * @return the next four bytes of this file, interpreted as a 939 * {@code float}. 940 * @exception EOFException if this file reaches the end before reading 941 * four bytes. 942 * @exception IOException if an I/O error occurs. 943 * @see java.io.RandomAccessFile#readInt() 944 * @see java.lang.Float#intBitsToFloat(int) 945 */ readFloat()946 public final float readFloat() throws IOException { 947 return Float.intBitsToFloat(readInt()); 948 } 949 950 /** 951 * Reads a {@code double} from this file. This method reads a 952 * {@code long} value, starting at the current file pointer, 953 * as if by the {@code readLong} method 954 * and then converts that {@code long} to a {@code double} 955 * using the {@code longBitsToDouble} method in 956 * class {@code Double}. 957 * <p> 958 * This method blocks until the eight bytes are read, the end of the 959 * stream is detected, or an exception is thrown. 960 * 961 * @return the next eight bytes of this file, interpreted as a 962 * {@code double}. 963 * @exception EOFException if this file reaches the end before reading 964 * eight bytes. 965 * @exception IOException if an I/O error occurs. 966 * @see java.io.RandomAccessFile#readLong() 967 * @see java.lang.Double#longBitsToDouble(long) 968 */ readDouble()969 public final double readDouble() throws IOException { 970 return Double.longBitsToDouble(readLong()); 971 } 972 973 /** 974 * Reads the next line of text from this file. This method successively 975 * reads bytes from the file, starting at the current file pointer, 976 * until it reaches a line terminator or the end 977 * of the file. Each byte is converted into a character by taking the 978 * byte's value for the lower eight bits of the character and setting the 979 * high eight bits of the character to zero. This method does not, 980 * therefore, support the full Unicode character set. 981 * 982 * <p> A line of text is terminated by a carriage-return character 983 * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a 984 * carriage-return character immediately followed by a newline character, 985 * or the end of the file. Line-terminating characters are discarded and 986 * are not included as part of the string returned. 987 * 988 * <p> This method blocks until a newline character is read, a carriage 989 * return and the byte following it are read (to see if it is a newline), 990 * the end of the file is reached, or an exception is thrown. 991 * 992 * @return the next line of text from this file, or null if end 993 * of file is encountered before even one byte is read. 994 * @exception IOException if an I/O error occurs. 995 */ 996 readLine()997 public final String readLine() throws IOException { 998 StringBuffer input = new StringBuffer(); 999 int c = -1; 1000 boolean eol = false; 1001 1002 while (!eol) { 1003 switch (c = read()) { 1004 case -1: 1005 case '\n': 1006 eol = true; 1007 break; 1008 case '\r': 1009 eol = true; 1010 long cur = getFilePointer(); 1011 if ((read()) != '\n') { 1012 seek(cur); 1013 } 1014 break; 1015 default: 1016 input.append((char)c); 1017 break; 1018 } 1019 } 1020 1021 if ((c == -1) && (input.length() == 0)) { 1022 return null; 1023 } 1024 return input.toString(); 1025 } 1026 1027 /** 1028 * Reads in a string from this file. The string has been encoded 1029 * using a 1030 * <a href="DataInput.html#modified-utf-8">modified UTF-8</a> 1031 * format. 1032 * <p> 1033 * The first two bytes are read, starting from the current file 1034 * pointer, as if by 1035 * {@code readUnsignedShort}. This value gives the number of 1036 * following bytes that are in the encoded string, not 1037 * the length of the resulting string. The following bytes are then 1038 * interpreted as bytes encoding characters in the modified UTF-8 format 1039 * and are converted into characters. 1040 * <p> 1041 * This method blocks until all the bytes are read, the end of the 1042 * stream is detected, or an exception is thrown. 1043 * 1044 * @return a Unicode string. 1045 * @exception EOFException if this file reaches the end before 1046 * reading all the bytes. 1047 * @exception IOException if an I/O error occurs. 1048 * @exception UTFDataFormatException if the bytes do not represent 1049 * valid modified UTF-8 encoding of a Unicode string. 1050 * @see java.io.RandomAccessFile#readUnsignedShort() 1051 */ readUTF()1052 public final String readUTF() throws IOException { 1053 return DataInputStream.readUTF(this); 1054 } 1055 1056 /** 1057 * Writes a {@code boolean} to the file as a one-byte value. The 1058 * value {@code true} is written out as the value 1059 * {@code (byte)1}; the value {@code false} is written out 1060 * as the value {@code (byte)0}. The write starts at 1061 * the current position of the file pointer. 1062 * 1063 * @param v a {@code boolean} value to be written. 1064 * @exception IOException if an I/O error occurs. 1065 */ writeBoolean(boolean v)1066 public final void writeBoolean(boolean v) throws IOException { 1067 write(v ? 1 : 0); 1068 //written++; 1069 } 1070 1071 /** 1072 * Writes a {@code byte} to the file as a one-byte value. The 1073 * write starts at the current position of the file pointer. 1074 * 1075 * @param v a {@code byte} value to be written. 1076 * @exception IOException if an I/O error occurs. 1077 */ writeByte(int v)1078 public final void writeByte(int v) throws IOException { 1079 write(v); 1080 //written++; 1081 } 1082 1083 /** 1084 * Writes a {@code short} to the file as two bytes, high byte first. 1085 * The write starts at the current position of the file pointer. 1086 * 1087 * @param v a {@code short} to be written. 1088 * @exception IOException if an I/O error occurs. 1089 */ writeShort(int v)1090 public final void writeShort(int v) throws IOException { 1091 write((v >>> 8) & 0xFF); 1092 write((v >>> 0) & 0xFF); 1093 //written += 2; 1094 } 1095 1096 /** 1097 * Writes a {@code char} to the file as a two-byte value, high 1098 * byte first. The write starts at the current position of the 1099 * file pointer. 1100 * 1101 * @param v a {@code char} value to be written. 1102 * @exception IOException if an I/O error occurs. 1103 */ writeChar(int v)1104 public final void writeChar(int v) throws IOException { 1105 write((v >>> 8) & 0xFF); 1106 write((v >>> 0) & 0xFF); 1107 //written += 2; 1108 } 1109 1110 /** 1111 * Writes an {@code int} to the file as four bytes, high byte first. 1112 * The write starts at the current position of the file pointer. 1113 * 1114 * @param v an {@code int} to be written. 1115 * @exception IOException if an I/O error occurs. 1116 */ writeInt(int v)1117 public final void writeInt(int v) throws IOException { 1118 write((v >>> 24) & 0xFF); 1119 write((v >>> 16) & 0xFF); 1120 write((v >>> 8) & 0xFF); 1121 write((v >>> 0) & 0xFF); 1122 //written += 4; 1123 } 1124 1125 /** 1126 * Writes a {@code long} to the file as eight bytes, high byte first. 1127 * The write starts at the current position of the file pointer. 1128 * 1129 * @param v a {@code long} to be written. 1130 * @exception IOException if an I/O error occurs. 1131 */ writeLong(long v)1132 public final void writeLong(long v) throws IOException { 1133 write((int)(v >>> 56) & 0xFF); 1134 write((int)(v >>> 48) & 0xFF); 1135 write((int)(v >>> 40) & 0xFF); 1136 write((int)(v >>> 32) & 0xFF); 1137 write((int)(v >>> 24) & 0xFF); 1138 write((int)(v >>> 16) & 0xFF); 1139 write((int)(v >>> 8) & 0xFF); 1140 write((int)(v >>> 0) & 0xFF); 1141 //written += 8; 1142 } 1143 1144 /** 1145 * Converts the float argument to an {@code int} using the 1146 * {@code floatToIntBits} method in class {@code Float}, 1147 * and then writes that {@code int} value to the file as a 1148 * four-byte quantity, high byte first. The write starts at the 1149 * current position of the file pointer. 1150 * 1151 * @param v a {@code float} value to be written. 1152 * @exception IOException if an I/O error occurs. 1153 * @see java.lang.Float#floatToIntBits(float) 1154 */ writeFloat(float v)1155 public final void writeFloat(float v) throws IOException { 1156 writeInt(Float.floatToIntBits(v)); 1157 } 1158 1159 /** 1160 * Converts the double argument to a {@code long} using the 1161 * {@code doubleToLongBits} method in class {@code Double}, 1162 * and then writes that {@code long} value to the file as an 1163 * eight-byte quantity, high byte first. The write starts at the current 1164 * position of the file pointer. 1165 * 1166 * @param v a {@code double} value to be written. 1167 * @exception IOException if an I/O error occurs. 1168 * @see java.lang.Double#doubleToLongBits(double) 1169 */ writeDouble(double v)1170 public final void writeDouble(double v) throws IOException { 1171 writeLong(Double.doubleToLongBits(v)); 1172 } 1173 1174 /** 1175 * Writes the string to the file as a sequence of bytes. Each 1176 * character in the string is written out, in sequence, by discarding 1177 * its high eight bits. The write starts at the current position of 1178 * the file pointer. 1179 * 1180 * @param s a string of bytes to be written. 1181 * @exception IOException if an I/O error occurs. 1182 */ 1183 @SuppressWarnings("deprecation") writeBytes(String s)1184 public final void writeBytes(String s) throws IOException { 1185 int len = s.length(); 1186 byte[] b = new byte[len]; 1187 s.getBytes(0, len, b, 0); 1188 writeBytes(b, 0, len); 1189 } 1190 1191 /** 1192 * Writes a string to the file as a sequence of characters. Each 1193 * character is written to the data output stream as if by the 1194 * {@code writeChar} method. The write starts at the current 1195 * position of the file pointer. 1196 * 1197 * @param s a {@code String} value to be written. 1198 * @exception IOException if an I/O error occurs. 1199 * @see java.io.RandomAccessFile#writeChar(int) 1200 */ writeChars(String s)1201 public final void writeChars(String s) throws IOException { 1202 int clen = s.length(); 1203 int blen = 2*clen; 1204 byte[] b = new byte[blen]; 1205 char[] c = new char[clen]; 1206 s.getChars(0, clen, c, 0); 1207 for (int i = 0, j = 0; i < clen; i++) { 1208 b[j++] = (byte)(c[i] >>> 8); 1209 b[j++] = (byte)(c[i] >>> 0); 1210 } 1211 writeBytes(b, 0, blen); 1212 } 1213 1214 /** 1215 * Writes a string to the file using 1216 * <a href="DataInput.html#modified-utf-8">modified UTF-8</a> 1217 * encoding in a machine-independent manner. 1218 * <p> 1219 * First, two bytes are written to the file, starting at the 1220 * current file pointer, as if by the 1221 * {@code writeShort} method giving the number of bytes to 1222 * follow. This value is the number of bytes actually written out, 1223 * not the length of the string. Following the length, each character 1224 * of the string is output, in sequence, using the modified UTF-8 encoding 1225 * for each character. 1226 * 1227 * @param str a string to be written. 1228 * @exception IOException if an I/O error occurs. 1229 */ writeUTF(String str)1230 public final void writeUTF(String str) throws IOException { 1231 DataOutputStream.writeUTF(str, this); 1232 } 1233 1234 // Android-added: use finalize() to detect if not close()d. finalize()1235 @Override protected void finalize() throws Throwable { 1236 try { 1237 if (guard != null) { 1238 guard.warnIfOpen(); 1239 } 1240 close(); 1241 } finally { 1242 super.finalize(); 1243 } 1244 } 1245 } 1246