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