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