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