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