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