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      * @throws     IndexOutOfBoundsException {@inheritDoc}
 589      */
 590     public void write(byte[] b, int off, int len) throws IOException {
 591         writeBytes(b, off, len);
 592     }
 593 
 594     // 'Random access' stuff
 595 
 596     /**
 597      * Returns the current offset in this file.
 598      *
 599      * @return     the offset from the beginning of the file, in bytes,
 600      *             at which the next read or write occurs.
 601      * @throws     IOException  if an I/O error occurs.
 602      */
 603     public native long getFilePointer() throws IOException;
 604 
 605     /**
 606      * Sets the file-pointer offset, measured from the beginning of this
 607      * file, at which the next read or write occurs.  The offset may be
 608      * set beyond the end of the file. Setting the offset beyond the end
 609      * of the file does not change the file length.  The file length will
 610      * change only by writing after the offset has been set beyond the end
 611      * of the file.
 612      *
 613      * @param      pos   the offset position, measured in bytes from the
 614      *                   beginning of the file, at which to set the file
 615      *                   pointer.
 616      * @throws     IOException  if {@code pos} is less than
 617      *                          {@code 0} or if an I/O error occurs.
 618      */
 619     public void seek(long pos) throws IOException {
 620         if (pos < 0) {
 621             throw new IOException("Negative seek offset");
 622         }
 623         if (Thread.currentThread().isVirtual()) {
 624             Blocker.managedBlock(() -> seek0(pos));
 625         } else {
 626             seek0(pos);
 627         }
 628     }
 629 
 630     private native void seek0(long pos) throws IOException;
 631 
 632     /**
 633      * Returns the length of this file.
 634      *
 635      * @return     the length of this file, measured in bytes.
 636      * @throws     IOException  if an I/O error occurs.
 637      */
 638     public long length() throws IOException {
 639         if (Thread.currentThread().isVirtual()) {
 640             return Blocker.managedBlock(() -> length0());
 641         } else {
 642             return length0();
 643         }
 644     }
 645 
 646     private native long length0() throws IOException;
 647 
 648     /**
 649      * Sets the length of this file.
 650      *
 651      * <p> If the present length of the file as returned by the
 652      * {@code length} method is greater than the {@code newLength}
 653      * argument then the file will be truncated.  In this case, if the file
 654      * offset as returned by the {@code getFilePointer} method is greater
 655      * than {@code newLength} then after this method returns the offset
 656      * will be equal to {@code newLength}.
 657      *
 658      * <p> If the present length of the file as returned by the
 659      * {@code length} method is smaller than the {@code newLength}
 660      * argument then the file will be extended.  In this case, the contents of
 661      * the extended portion of the file are not defined.
 662      *
 663      * @param      newLength    The desired length of the file
 664      * @throws     IOException  If an I/O error occurs
 665      * @since      1.2
 666      */
 667     public void setLength(long newLength) throws IOException {
 668         if (Thread.currentThread().isVirtual()) {
 669             Blocker.managedBlock(() -> setLength0(newLength));
 670         } else {
 671             setLength0(newLength);
 672         }
 673     }
 674 
 675     private native void setLength0(long newLength) throws IOException;
 676 
 677     /**
 678      * Closes this random access file stream and releases any system
 679      * resources associated with the stream. A closed random access
 680      * file cannot perform input or output operations and cannot be
 681      * reopened.
 682      *
 683      * <p> If this file has an associated channel then the channel is closed
 684      * as well.
 685      *
 686      * @throws     IOException  if an I/O error occurs.
 687      *
 688      * @revised 1.4
 689      */
 690     public void close() throws IOException {
 691         if (closed) {
 692             return;
 693         }
 694         synchronized (closeLock) {
 695             if (closed) {
 696                 return;
 697             }
 698             closed = true;
 699         }
 700 
 701         FileChannel fc = channel;
 702         if (fc != null) {
 703             // possible race with getChannel(), benign since
 704             // FileChannel.close is final and idempotent
 705             fc.close();
 706         }
 707 
 708         fd.closeAll(new Closeable() {
 709             public void close() throws IOException {
 710                fd.close();
 711            }
 712         });
 713     }
 714 
 715     //
 716     //  Some "reading/writing Java data types" methods stolen from
 717     //  DataInputStream and DataOutputStream.
 718     //
 719 
 720     /**
 721      * Reads a {@code boolean} from this file. This method reads a
 722      * single byte from the file, starting at the current file pointer.
 723      * A value of {@code 0} represents
 724      * {@code false}. Any other value represents {@code true}.
 725      * This method blocks until the byte is read, the end of the stream
 726      * is detected, or an exception is thrown.
 727      *
 728      * @return     the {@code boolean} value read.
 729      * @throws     EOFException  if this file has reached the end.
 730      * @throws     IOException   if an I/O error occurs.
 731      */
 732     public final boolean readBoolean() throws IOException {
 733         int ch = this.read();
 734         if (ch < 0)
 735             throw new EOFException();
 736         return (ch != 0);
 737     }
 738 
 739     /**
 740      * Reads a signed eight-bit value from this file. This method reads a
 741      * byte from the file, starting from the current file pointer.
 742      * If the byte read is {@code b}, where
 743      * {@code 0 <= b <= 255},
 744      * then the result is:
 745      * <blockquote><pre>
 746      *     (byte)(b)
 747      * </pre></blockquote>
 748      * <p>
 749      * This method blocks until the byte is read, the end of the stream
 750      * is detected, or an exception is thrown.
 751      *
 752      * @return     the next byte of this file as a signed eight-bit
 753      *             {@code byte}.
 754      * @throws     EOFException  if this file has reached the end.
 755      * @throws     IOException   if an I/O error occurs.
 756      */
 757     public final byte readByte() throws IOException {
 758         int ch = this.read();
 759         if (ch < 0)
 760             throw new EOFException();
 761         return (byte)(ch);
 762     }
 763 
 764     /**
 765      * Reads an unsigned eight-bit number from this file. This method reads
 766      * a byte from this file, starting at the current file pointer,
 767      * and returns that byte.
 768      * <p>
 769      * This method blocks until the byte is read, the end of the stream
 770      * is detected, or an exception is thrown.
 771      *
 772      * @return     the next byte of this file, interpreted as an unsigned
 773      *             eight-bit number.
 774      * @throws     EOFException  if this file has reached the end.
 775      * @throws     IOException   if an I/O error occurs.
 776      */
 777     public final int readUnsignedByte() throws IOException {
 778         int ch = this.read();
 779         if (ch < 0)
 780             throw new EOFException();
 781         return ch;
 782     }
 783 
 784     /**
 785      * Reads a signed 16-bit number from this file. The method reads two
 786      * bytes from this file, starting at the current file pointer.
 787      * If the two bytes read, in order, are
 788      * {@code b1} and {@code b2}, where each of the two values is
 789      * between {@code 0} and {@code 255}, inclusive, then the
 790      * result is equal to:
 791      * <blockquote><pre>
 792      *     (short)((b1 &lt;&lt; 8) | b2)
 793      * </pre></blockquote>
 794      * <p>
 795      * This method blocks until the two bytes are read, the end of the
 796      * stream is detected, or an exception is thrown.
 797      *
 798      * @return     the next two bytes of this file, interpreted as a signed
 799      *             16-bit number.
 800      * @throws     EOFException  if this file reaches the end before reading
 801      *               two bytes.
 802      * @throws     IOException   if an I/O error occurs.
 803      */
 804     public final short readShort() throws IOException {
 805         int ch1 = this.read();
 806         int ch2 = this.read();
 807         if ((ch1 | ch2) < 0)
 808             throw new EOFException();
 809         return (short)((ch1 << 8) + (ch2 << 0));
 810     }
 811 
 812     /**
 813      * Reads an unsigned 16-bit number from this file. This method reads
 814      * two bytes from the file, starting at the current file pointer.
 815      * If the bytes read, in order, are
 816      * {@code b1} and {@code b2}, where
 817      * {@code 0 <= b1, b2 <= 255},
 818      * then the result is equal to:
 819      * <blockquote><pre>
 820      *     (b1 &lt;&lt; 8) | b2
 821      * </pre></blockquote>
 822      * <p>
 823      * This method blocks until the two bytes are read, the end of the
 824      * stream is detected, or an exception is thrown.
 825      *
 826      * @return     the next two bytes of this file, interpreted as an unsigned
 827      *             16-bit integer.
 828      * @throws     EOFException  if this file reaches the end before reading
 829      *               two bytes.
 830      * @throws     IOException   if an I/O error occurs.
 831      */
 832     public final int readUnsignedShort() throws IOException {
 833         int ch1 = this.read();
 834         int ch2 = this.read();
 835         if ((ch1 | ch2) < 0)
 836             throw new EOFException();
 837         return (ch1 << 8) + (ch2 << 0);
 838     }
 839 
 840     /**
 841      * Reads a character from this file. This method reads two
 842      * bytes from the file, starting at the current file pointer.
 843      * If the bytes read, in order, are
 844      * {@code b1} and {@code b2}, where
 845      * {@code 0 <= b1, b2 <= 255},
 846      * then the result is equal to:
 847      * <blockquote><pre>
 848      *     (char)((b1 &lt;&lt; 8) | b2)
 849      * </pre></blockquote>
 850      * <p>
 851      * This method blocks until the two bytes are read, the end of the
 852      * stream is detected, or an exception is thrown.
 853      *
 854      * @return     the next two bytes of this file, interpreted as a
 855      *                  {@code char}.
 856      * @throws     EOFException  if this file reaches the end before reading
 857      *               two bytes.
 858      * @throws     IOException   if an I/O error occurs.
 859      */
 860     public final char readChar() throws IOException {
 861         int ch1 = this.read();
 862         int ch2 = this.read();
 863         if ((ch1 | ch2) < 0)
 864             throw new EOFException();
 865         return (char)((ch1 << 8) + (ch2 << 0));
 866     }
 867 
 868     /**
 869      * Reads a signed 32-bit integer from this file. This method reads 4
 870      * bytes from the file, starting at the current file pointer.
 871      * If the bytes read, in order, are {@code b1},
 872      * {@code b2}, {@code b3}, and {@code b4}, where
 873      * {@code 0 <= b1, b2, b3, b4 <= 255},
 874      * then the result is equal to:
 875      * <blockquote><pre>
 876      *     (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4
 877      * </pre></blockquote>
 878      * <p>
 879      * This method blocks until the four bytes are read, the end of the
 880      * stream is detected, or an exception is thrown.
 881      *
 882      * @return     the next four bytes of this file, interpreted as an
 883      *             {@code int}.
 884      * @throws     EOFException  if this file reaches the end before reading
 885      *               four bytes.
 886      * @throws     IOException   if an I/O error occurs.
 887      */
 888     public final int readInt() throws IOException {
 889         int ch1 = this.read();
 890         int ch2 = this.read();
 891         int ch3 = this.read();
 892         int ch4 = this.read();
 893         if ((ch1 | ch2 | ch3 | ch4) < 0)
 894             throw new EOFException();
 895         return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
 896     }
 897 
 898     /**
 899      * Reads a signed 64-bit integer from this file. This method reads eight
 900      * bytes from the file, starting at the current file pointer.
 901      * If the bytes read, in order, are
 902      * {@code b1}, {@code b2}, {@code b3},
 903      * {@code b4}, {@code b5}, {@code b6},
 904      * {@code b7}, and {@code b8,} where:
 905      * <blockquote><pre>
 906      *     0 &lt;= b1, b2, b3, b4, b5, b6, b7, b8 &lt;=255,
 907      * </pre></blockquote>
 908      * <p>
 909      * then the result is equal to:
 910      * <blockquote><pre>
 911      *     ((long)b1 &lt;&lt; 56) + ((long)b2 &lt;&lt; 48)
 912      *     + ((long)b3 &lt;&lt; 40) + ((long)b4 &lt;&lt; 32)
 913      *     + ((long)b5 &lt;&lt; 24) + ((long)b6 &lt;&lt; 16)
 914      *     + ((long)b7 &lt;&lt; 8) + b8
 915      * </pre></blockquote>
 916      * <p>
 917      * This method blocks until the eight bytes are read, the end of the
 918      * stream is detected, or an exception is thrown.
 919      *
 920      * @return     the next eight bytes of this file, interpreted as a
 921      *             {@code long}.
 922      * @throws     EOFException  if this file reaches the end before reading
 923      *               eight bytes.
 924      * @throws     IOException   if an I/O error occurs.
 925      */
 926     public final long readLong() throws IOException {
 927         return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
 928     }
 929 
 930     /**
 931      * Reads a {@code float} from this file. This method reads an
 932      * {@code int} value, starting at the current file pointer,
 933      * as if by the {@code readInt} method
 934      * and then converts that {@code int} to a {@code float}
 935      * using the {@code intBitsToFloat} method in class
 936      * {@code Float}.
 937      * <p>
 938      * This method blocks until the four bytes are read, the end of the
 939      * stream is detected, or an exception is thrown.
 940      *
 941      * @return     the next four bytes of this file, interpreted as a
 942      *             {@code float}.
 943      * @throws     EOFException  if this file reaches the end before reading
 944      *             four bytes.
 945      * @throws     IOException   if an I/O error occurs.
 946      * @see        java.io.RandomAccessFile#readInt()
 947      * @see        java.lang.Float#intBitsToFloat(int)
 948      */
 949     public final float readFloat() throws IOException {
 950         return Float.intBitsToFloat(readInt());
 951     }
 952 
 953     /**
 954      * Reads a {@code double} from this file. This method reads a
 955      * {@code long} value, starting at the current file pointer,
 956      * as if by the {@code readLong} method
 957      * and then converts that {@code long} to a {@code double}
 958      * using the {@code longBitsToDouble} method in
 959      * class {@code Double}.
 960      * <p>
 961      * This method blocks until the eight bytes are read, the end of the
 962      * stream is detected, or an exception is thrown.
 963      *
 964      * @return     the next eight bytes of this file, interpreted as a
 965      *             {@code double}.
 966      * @throws     EOFException  if this file reaches the end before reading
 967      *             eight bytes.
 968      * @throws     IOException   if an I/O error occurs.
 969      * @see        java.io.RandomAccessFile#readLong()
 970      * @see        java.lang.Double#longBitsToDouble(long)
 971      */
 972     public final double readDouble() throws IOException {
 973         return Double.longBitsToDouble(readLong());
 974     }
 975 
 976     /**
 977      * Reads the next line of text from this file.  This method successively
 978      * reads bytes from the file, starting at the current file pointer,
 979      * until it reaches a line terminator or the end
 980      * of the file.  Each byte is converted into a character by taking the
 981      * byte's value for the lower eight bits of the character and setting the
 982      * high eight bits of the character to zero.  This method does not,
 983      * therefore, support the full Unicode character set.
 984      *
 985      * <p> A line of text is terminated by a carriage-return character
 986      * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a
 987      * carriage-return character immediately followed by a newline character,
 988      * or the end of the file.  Line-terminating characters are discarded and
 989      * are not included as part of the string returned.
 990      *
 991      * <p> This method blocks until a newline character is read, a carriage
 992      * return and the byte following it are read (to see if it is a newline),
 993      * the end of the file is reached, or an exception is thrown.
 994      *
 995      * @return     the next line of text from this file, or null if end
 996      *             of file is encountered before even one byte is read.
 997      * @throws     IOException  if an I/O error occurs.
 998      */
 999 
1000     public final String readLine() throws IOException {
1001         StringBuilder input = new StringBuilder();
1002         int c = -1;
1003         boolean eol = false;
1004 
1005         while (!eol) {
1006             switch (c = read()) {
1007             case -1:
1008             case '\n':
1009                 eol = true;
1010                 break;
1011             case '\r':
1012                 eol = true;
1013                 long cur = getFilePointer();
1014                 if ((read()) != '\n') {
1015                     seek(cur);
1016                 }
1017                 break;
1018             default:
1019                 input.append((char)c);
1020                 break;
1021             }
1022         }
1023 
1024         if ((c == -1) && (input.length() == 0)) {
1025             return null;
1026         }
1027         return input.toString();
1028     }
1029 
1030     /**
1031      * Reads in a string from this file. The string has been encoded
1032      * using a
1033      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1034      * format.
1035      * <p>
1036      * The first two bytes are read, starting from the current file
1037      * pointer, as if by
1038      * {@code readUnsignedShort}. This value gives the number of
1039      * following bytes that are in the encoded string, not
1040      * the length of the resulting string. The following bytes are then
1041      * interpreted as bytes encoding characters in the modified UTF-8 format
1042      * and are converted into characters.
1043      * <p>
1044      * This method blocks until all the bytes are read, the end of the
1045      * stream is detected, or an exception is thrown.
1046      *
1047      * @return     a Unicode string.
1048      * @throws     EOFException            if this file reaches the end before
1049      *               reading all the bytes.
1050      * @throws     IOException             if an I/O error occurs.
1051      * @throws     UTFDataFormatException  if the bytes do not represent
1052      *               valid modified UTF-8 encoding of a Unicode string.
1053      * @see        java.io.RandomAccessFile#readUnsignedShort()
1054      */
1055     public final String readUTF() throws IOException {
1056         return DataInputStream.readUTF(this);
1057     }
1058 
1059     /**
1060      * Writes a {@code boolean} to the file as a one-byte value. The
1061      * value {@code true} is written out as the value
1062      * {@code (byte)1}; the value {@code false} is written out
1063      * as the value {@code (byte)0}. The write starts at
1064      * the current position of the file pointer.
1065      *
1066      * @param      v   a {@code boolean} value to be written.
1067      * @throws     IOException  if an I/O error occurs.
1068      */
1069     public final void writeBoolean(boolean v) throws IOException {
1070         write(v ? 1 : 0);
1071         //written++;
1072     }
1073 
1074     /**
1075      * Writes a {@code byte} to the file as a one-byte value. The
1076      * write starts at the current position of the file pointer.
1077      *
1078      * @param      v   a {@code byte} value to be written.
1079      * @throws     IOException  if an I/O error occurs.
1080      */
1081     public final void writeByte(int v) throws IOException {
1082         write(v);
1083         //written++;
1084     }
1085 
1086     /**
1087      * Writes a {@code short} to the file as two bytes, high byte first.
1088      * The write starts at the current position of the file pointer.
1089      *
1090      * @param      v   a {@code short} to be written.
1091      * @throws     IOException  if an I/O error occurs.
1092      */
1093     public final void writeShort(int v) throws IOException {
1094         write((v >>> 8) & 0xFF);
1095         write((v >>> 0) & 0xFF);
1096         //written += 2;
1097     }
1098 
1099     /**
1100      * Writes a {@code char} to the file as a two-byte value, high
1101      * byte first. The write starts at the current position of the
1102      * file pointer.
1103      *
1104      * @param      v   a {@code char} value to be written.
1105      * @throws     IOException  if an I/O error occurs.
1106      */
1107     public final void writeChar(int v) throws IOException {
1108         write((v >>> 8) & 0xFF);
1109         write((v >>> 0) & 0xFF);
1110         //written += 2;
1111     }
1112 
1113     /**
1114      * Writes an {@code int} to the file as four bytes, high byte first.
1115      * The write starts at the current position of the file pointer.
1116      *
1117      * @param      v   an {@code int} to be written.
1118      * @throws     IOException  if an I/O error occurs.
1119      */
1120     public final void writeInt(int v) throws IOException {
1121         write((v >>> 24) & 0xFF);
1122         write((v >>> 16) & 0xFF);
1123         write((v >>>  8) & 0xFF);
1124         write((v >>>  0) & 0xFF);
1125         //written += 4;
1126     }
1127 
1128     /**
1129      * Writes a {@code long} to the file as eight bytes, high byte first.
1130      * The write starts at the current position of the file pointer.
1131      *
1132      * @param      v   a {@code long} to be written.
1133      * @throws     IOException  if an I/O error occurs.
1134      */
1135     public final void writeLong(long v) throws IOException {
1136         write((int)(v >>> 56) & 0xFF);
1137         write((int)(v >>> 48) & 0xFF);
1138         write((int)(v >>> 40) & 0xFF);
1139         write((int)(v >>> 32) & 0xFF);
1140         write((int)(v >>> 24) & 0xFF);
1141         write((int)(v >>> 16) & 0xFF);
1142         write((int)(v >>>  8) & 0xFF);
1143         write((int)(v >>>  0) & 0xFF);
1144         //written += 8;
1145     }
1146 
1147     /**
1148      * Converts the float argument to an {@code int} using the
1149      * {@code floatToIntBits} method in class {@code Float},
1150      * and then writes that {@code int} value to the file as a
1151      * four-byte quantity, high byte first. The write starts at the
1152      * current position of the file pointer.
1153      *
1154      * @param      v   a {@code float} value to be written.
1155      * @throws     IOException  if an I/O error occurs.
1156      * @see        java.lang.Float#floatToIntBits(float)
1157      */
1158     public final void writeFloat(float v) throws IOException {
1159         writeInt(Float.floatToIntBits(v));
1160     }
1161 
1162     /**
1163      * Converts the double argument to a {@code long} using the
1164      * {@code doubleToLongBits} method in class {@code Double},
1165      * and then writes that {@code long} value to the file as an
1166      * eight-byte quantity, high byte first. The write starts at the current
1167      * position of the file pointer.
1168      *
1169      * @param      v   a {@code double} value to be written.
1170      * @throws     IOException  if an I/O error occurs.
1171      * @see        java.lang.Double#doubleToLongBits(double)
1172      */
1173     public final void writeDouble(double v) throws IOException {
1174         writeLong(Double.doubleToLongBits(v));
1175     }
1176 
1177     /**
1178      * Writes the string to the file as a sequence of bytes. Each
1179      * character in the string is written out, in sequence, by discarding
1180      * its high eight bits. The write starts at the current position of
1181      * the file pointer.
1182      *
1183      * @param      s   a string of bytes to be written.
1184      * @throws     IOException  if an I/O error occurs.
1185      */
1186     @SuppressWarnings("deprecation")
1187     public final void writeBytes(String s) throws IOException {
1188         int len = s.length();
1189         byte[] b = new byte[len];
1190         s.getBytes(0, len, b, 0);
1191         writeBytes(b, 0, len);
1192     }
1193 
1194     /**
1195      * Writes a string to the file as a sequence of characters. Each
1196      * character is written to the data output stream as if by the
1197      * {@code writeChar} method. The write starts at the current
1198      * position of the file pointer.
1199      *
1200      * @param      s   a {@code String} value to be written.
1201      * @throws     IOException  if an I/O error occurs.
1202      * @see        java.io.RandomAccessFile#writeChar(int)
1203      */
1204     public final void writeChars(String s) throws IOException {
1205         int clen = s.length();
1206         int blen = 2*clen;
1207         byte[] b = new byte[blen];
1208         char[] c = new char[clen];
1209         s.getChars(0, clen, c, 0);
1210         for (int i = 0, j = 0; i < clen; i++) {
1211             b[j++] = (byte)(c[i] >>> 8);
1212             b[j++] = (byte)(c[i] >>> 0);
1213         }
1214         writeBytes(b, 0, blen);
1215     }
1216 
1217     /**
1218      * Writes a string to the file using
1219      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1220      * encoding in a machine-independent manner.
1221      * <p>
1222      * First, two bytes are written to the file, starting at the
1223      * current file pointer, as if by the
1224      * {@code writeShort} method giving the number of bytes to
1225      * follow. This value is the number of bytes actually written out,
1226      * not the length of the string. Following the length, each character
1227      * of the string is output, in sequence, using the modified UTF-8 encoding
1228      * for each character.
1229      *
1230      * @param      str   a string to be written.
1231      * @throws     IOException  if an I/O error occurs.
1232      */
1233     public final void writeUTF(String str) throws IOException {
1234         DataOutputStream.writeUTF(str, this);
1235     }
1236 
1237     private static native void initIDs();
1238 
1239     static {
1240         initIDs();
1241         SharedSecrets.setJavaIORandomAccessFileAccess(new JavaIORandomAccessFileAccess()
1242         {
1243             // This is for j.u.z.ZipFile.OPEN_DELETE. The O_TEMPORARY flag
1244             // is only implemented/supported on windows.
1245             public RandomAccessFile openAndDelete(File file, String mode)
1246                 throws IOException
1247             {
1248                 return new RandomAccessFile(file, mode, true);
1249             }
1250         });
1251     }
1252 }
--- EOF ---