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