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 sun.nio.ch.FileChannelImpl;
  33 
  34 
  35 /**
  36  * Instances of this class support both reading and writing to a
  37  * random access file. A random access file behaves like a large
  38  * array of bytes stored in the file system. There is a kind of cursor,
  39  * or index into the implied array, called the <em>file pointer</em>;
  40  * input operations read bytes starting at the file pointer and advance
  41  * the file pointer past the bytes read. If the random access file is
  42  * created in read/write mode, then output operations are also available;
  43  * output operations write bytes starting at the file pointer and advance
  44  * the file pointer past the bytes written. Output operations that write
  45  * past the current end of the implied array cause the array to be
  46  * extended. The file pointer can be read by the
  47  * {@code getFilePointer} method and set by the {@code seek}
  48  * method.
  49  * <p>
  50  * It is generally true of all the reading routines in this class that
  51  * if end-of-file is reached before the desired number of bytes has been
  52  * read, an {@code EOFException} (which is a kind of
  53  * {@code IOException}) is thrown. If any byte cannot be read for
  54  * any reason other than end-of-file, an {@code IOException} other
  55  * than {@code EOFException} is thrown. In particular, an
  56  * {@code IOException} may be thrown if the stream has been closed.
  57  *
  58  * @since   1.0
  59  */
  60 
  61 public class RandomAccessFile implements DataOutput, DataInput, Closeable {
  62 
  63     private FileDescriptor fd;
  64     private volatile FileChannel channel;
  65     private boolean rw;
  66 
  67     /**
  68      * The path of the referenced file
  69      * (null if the stream is created with a file descriptor)
  70      */
  71     private final String path;
  72 
  73     private final Object closeLock = new Object();
  74 
  75     private volatile boolean closed;
  76 
  77     private static final int O_RDONLY = 1;
  78     private static final int O_RDWR =   2;
  79     private static final int O_SYNC =   4;
  80     private static final int O_DSYNC =  8;
  81     private static final int O_TEMPORARY =  16;
  82 
  83     /**
  84      * Creates a random access file stream to read from, and optionally
  85      * to write to, a file with the specified name. A new
  86      * {@link FileDescriptor} object is created to represent the
  87      * connection to the file.
  88      *
  89      * <p> The {@code mode} argument specifies the access mode with which the
  90      * file is to be opened.  The permitted values and their meanings are as
  91      * specified for the <a
  92      * href="#mode">{@code RandomAccessFile(File,String)}</a> constructor.
  93      *
  94      * <p>
  95      * If there is a security manager, its {@code checkRead} method
  96      * is called with the {@code name} argument
  97      * as its argument to see if read access to the file is allowed.
  98      * If the mode allows writing, the security manager's
  99      * {@code checkWrite} method
 100      * is also called with the {@code name} argument
 101      * as its argument to see if write access to the file is allowed.
 102      *
 103      * @param      name   the system-dependent filename
 104      * @param      mode   the access <a href="#mode">mode</a>
 105      * @throws     IllegalArgumentException  if the mode argument is not equal
 106      *             to one of {@code "r"}, {@code "rw"}, {@code "rws"}, or
 107      *             {@code "rwd"}
 108      * @throws     FileNotFoundException
 109      *             if the mode is {@code "r"} but the given string does not
 110      *             denote an existing regular file, or if the mode begins with
 111      *             {@code "rw"} but the given string does not denote an
 112      *             existing, writable regular file and a new regular file of
 113      *             that name cannot be created, or if some other error occurs
 114      *             while opening or creating the file
 115      * @throws      SecurityException   if a security manager exists and its
 116      *             {@code checkRead} method denies read access to the file
 117      *             or the mode is {@code "rw"} and the security manager's
 118      *             {@code checkWrite} method denies write access to the file
 119      * @see        java.lang.SecurityException
 120      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
 121      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 122      * @revised 1.4
 123      */
 124     public RandomAccessFile(String name, String mode)
 125         throws FileNotFoundException
 126     {
 127         this(name != null ? new File(name) : null, mode);
 128     }
 129 
 130     /**
 131      * Creates a random access file stream to read from, and optionally to
 132      * write to, the file specified by the {@link File} argument.  A new {@link
 133      * FileDescriptor} object is created to represent this file connection.
 134      *
 135      * <p>The <a id="mode">{@code mode}</a> argument specifies the access mode
 136      * in which the file is to be opened.  The permitted values and their
 137      * meanings are:
 138      *
 139      * <table class="striped">
 140      * <caption style="display:none">Access mode permitted values and meanings</caption>
 141      * <thead>
 142      * <tr><th scope="col" style="text-align:left">Value</th><th scope="col" style="text-align:left">Meaning</th></tr>
 143      * </thead>
 144      * <tbody>
 145      * <tr><th scope="row" style="vertical-align:top">{@code "r"}</th>
 146      *     <td> Open for reading only. Invoking any of the {@code write}
 147      *     methods of the resulting object will cause an
 148      *     {@link java.io.IOException} to be thrown.</td></tr>
 149      * <tr><th scope="row" style="vertical-align:top">{@code "rw"}</th>
 150      *     <td> Open for reading and writing.  If the file does not already
 151      *     exist then an attempt will be made to create it.</td></tr>
 152      * <tr><th scope="row" style="vertical-align:top">{@code "rws"}</th>
 153      *     <td> Open for reading and writing, as with {@code "rw"}, and also
 154      *     require that every update to the file's content or metadata be
 155      *     written synchronously to the underlying storage device.</td></tr>
 156      * <tr><th scope="row" style="vertical-align:top">{@code "rwd"}</th>
 157      *     <td> Open for reading and writing, as with {@code "rw"}, and also
 158      *     require that every update to the file's content be written
 159      *     synchronously to the underlying storage device.</td></tr>
 160      * </tbody>
 161      * </table>
 162      *
 163      * The {@code "rws"} and {@code "rwd"} modes work much like the {@link
 164      * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of
 165      * the {@link java.nio.channels.FileChannel} class, passing arguments of
 166      * {@code true} and {@code false}, respectively, except that they always
 167      * apply to every I/O operation and are therefore often more efficient.  If
 168      * the file resides on a local storage device then when an invocation of a
 169      * method of this class returns it is guaranteed that all changes made to
 170      * the file by that invocation will have been written to that device.  This
 171      * is useful for ensuring that critical information is not lost in the
 172      * event of a system crash.  If the file does not reside on a local device
 173      * then no such guarantee is made.
 174      *
 175      * <p>The {@code "rwd"} mode can be used to reduce the number of I/O
 176      * operations performed.  Using {@code "rwd"} only requires updates to the
 177      * file's content to be written to storage; using {@code "rws"} requires
 178      * updates to both the file's content and its metadata to be written, which
 179      * generally requires at least one more low-level I/O operation.
 180      *
 181      * <p>If there is a security manager, its {@code checkRead} method is
 182      * called with the pathname of the {@code file} argument as its
 183      * argument to see if read access to the file is allowed.  If the mode
 184      * allows writing, the security manager's {@code checkWrite} method is
 185      * also called with the path argument to see if write access to the file is
 186      * allowed.
 187      *
 188      * @param      file   the file object
 189      * @param      mode   the access mode, as described
 190      *                    <a href="#mode">above</a>
 191      * @throws     IllegalArgumentException  if the mode argument is not equal
 192      *             to one of {@code "r"}, {@code "rw"}, {@code "rws"}, or
 193      *             {@code "rwd"}
 194      * @throws     FileNotFoundException
 195      *             if the mode is {@code "r"} but the given file object does
 196      *             not denote an existing regular file, or if the mode begins
 197      *             with {@code "rw"} but the given file object does not denote
 198      *             an existing, writable regular file and a new regular file of
 199      *             that name cannot be created, or if some other error occurs
 200      *             while opening or creating the file
 201      * @throws      SecurityException  if a security manager exists and its
 202      *             {@code checkRead} method denies read access to the file
 203      *             or the mode is {@code "rw"} and the security manager's
 204      *             {@code checkWrite} method denies write access to the file
 205      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
 206      * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
 207      * @see        java.nio.channels.FileChannel#force(boolean)
 208      * @revised 1.4
 209      */
 210     public RandomAccessFile(File file, String mode)
 211         throws FileNotFoundException
 212     {
 213         this(file, mode, false);
 214     }
 215 
 216     private RandomAccessFile(File file, String mode, boolean openAndDelete)
 217         throws FileNotFoundException
 218     {
 219         String name = (file != null ? file.getPath() : null);
 220         int imode = -1;
 221         if (mode.equals("r"))
 222             imode = O_RDONLY;
 223         else if (mode.startsWith("rw")) {
 224             imode = O_RDWR;
 225             rw = true;
 226             if (mode.length() > 2) {
 227                 if (mode.equals("rws"))
 228                     imode |= O_SYNC;
 229                 else if (mode.equals("rwd"))
 230                     imode |= O_DSYNC;
 231                 else
 232                     imode = -1;
 233             }
 234         }
 235         if (openAndDelete)
 236             imode |= O_TEMPORARY;
 237         if (imode < 0)
 238             throw new IllegalArgumentException("Illegal mode \"" + mode
 239                                                + "\" must be one of "
 240                                                + "\"r\", \"rw\", \"rws\","
 241                                                + " or \"rwd\"");
 242         @SuppressWarnings("removal")
 243         SecurityManager security = System.getSecurityManager();
 244         if (security != null) {
 245             security.checkRead(name);
 246             if (rw) {
 247                 security.checkWrite(name);
 248             }
 249         }
 250         if (name == null) {
 251             throw new NullPointerException();
 252         }
 253         if (file.isInvalid()) {
 254             throw new FileNotFoundException("Invalid file path");
 255         }
 256         fd = new FileDescriptor();
 257         fd.attach(this);
 258         path = name;
 259         open(name, imode);
 260         FileCleanable.register(fd);   // open sets the fd, register the cleanup
 261     }
 262 
 263     /**
 264      * Returns the opaque file descriptor object associated with this
 265      * stream.
 266      *
 267      * @return     the file descriptor object associated with this stream.
 268      * @throws     IOException  if an I/O error occurs.
 269      * @see        java.io.FileDescriptor
 270      */
 271     public final FileDescriptor getFD() throws IOException {
 272         if (fd != null) {
 273             return fd;
 274         }
 275         throw new IOException();
 276     }
 277 
 278     /**
 279      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
 280      * object associated with this file.
 281      *
 282      * <p> The {@link java.nio.channels.FileChannel#position()
 283      * position} of the returned channel will always be equal to
 284      * this object's file-pointer offset as returned by the {@link
 285      * #getFilePointer getFilePointer} method.  Changing this object's
 286      * file-pointer offset, whether explicitly or by reading or writing bytes,
 287      * will change the position of the channel, and vice versa.  Changing the
 288      * file's length via this object will change the length seen via the file
 289      * channel, and vice versa.
 290      *
 291      * @return  the file channel associated with this file
 292      *
 293      * @since 1.4
 294      */
 295     public final FileChannel getChannel() {
 296         FileChannel fc = this.channel;
 297         if (fc == null) {
 298             synchronized (this) {
 299                 fc = this.channel;
 300                 if (fc == null) {
 301                     this.channel = fc = FileChannelImpl.open(fd, path, true,
 302                         rw, false, this);
 303                     if (closed) {
 304                         try {
 305                             fc.close();
 306                         } catch (IOException ioe) {
 307                             throw new InternalError(ioe); // should not happen
 308                         }
 309                     }
 310                 }
 311             }
 312         }
 313         return fc;
 314     }
 315 
 316     /**
 317      * Opens a file and returns the file descriptor.  The file is
 318      * opened in read-write mode if the O_RDWR bit in {@code mode}
 319      * is true, else the file is opened as read-only.
 320      * If the {@code name} refers to a directory, an IOException
 321      * is thrown.
 322      *
 323      * @param name the name of the file
 324      * @param mode the mode flags, a combination of the O_ constants
 325      *             defined above
 326      */
 327     private native void open0(String name, int mode)
 328         throws FileNotFoundException;
 329 
 330     // wrap native call to allow instrumentation
 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 void open(String name, int mode)
 343         throws FileNotFoundException {
 344         open0(name, mode);



 345     }
 346 
 347     // 'Read' primitives
 348 
 349     /**
 350      * Reads a byte of data from this file. The byte is returned as an
 351      * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This
 352      * method blocks if no input is yet available.
 353      * <p>
 354      * Although {@code RandomAccessFile} is not a subclass of
 355      * {@code InputStream}, this method behaves in exactly the same
 356      * way as the {@link InputStream#read()} method of
 357      * {@code InputStream}.
 358      *
 359      * @return     the next byte of data, or {@code -1} if the end of the
 360      *             file has been reached.
 361      * @throws     IOException  if an I/O error occurs. Not thrown if
 362      *                          end-of-file has been reached.
 363      */
 364     public int read() throws IOException {
 365         return read0();




 366     }
 367 
 368     private native int read0() throws IOException;
 369 
 370     /**
 371      * Reads a sub array as a sequence of bytes.
 372      * @param     b the buffer into which the data is read.
 373      * @param     off the start offset of the data.
 374      * @param     len the number of bytes to read.
 375      * @throws    IOException If an I/O error has occurred.
 376      */
 377     private native int readBytes(byte[] b, int off, int len) throws IOException;








 378 
 379     /**
 380      * Reads up to {@code len} bytes of data from this file into an
 381      * array of bytes. This method blocks until at least one byte of input
 382      * is available.
 383      * <p>
 384      * Although {@code RandomAccessFile} is not a subclass of
 385      * {@code InputStream}, this method behaves in exactly the
 386      * same way as the {@link InputStream#read(byte[], int, int)} method of
 387      * {@code InputStream}.
 388      *
 389      * @param      b     the buffer into which the data is read.
 390      * @param      off   the start offset in array {@code b}
 391      *                   at which the data is written.
 392      * @param      len   the maximum number of bytes read.
 393      * @return     the total number of bytes read into the buffer, or
 394      *             {@code -1} if there is no more data because the end of
 395      *             the file has been reached.
 396      * @throws     IOException If the first byte cannot be read for any reason
 397      *             other than end of file, or if the random access file has been closed,
 398      *             or if some other I/O error occurs.
 399      * @throws     NullPointerException If {@code b} is {@code null}.
 400      * @throws     IndexOutOfBoundsException If {@code off} is negative,
 401      *             {@code len} is negative, or {@code len} is greater than
 402      *             {@code b.length - off}
 403      */
 404     public int read(byte[] b, int off, int len) throws IOException {
 405         return readBytes(b, off, len);




 406     }
 407 
 408     /**
 409      * Reads up to {@code b.length} bytes of data from this file
 410      * into an array of bytes. This method blocks until at least one byte
 411      * of input is available.
 412      * <p>
 413      * Although {@code RandomAccessFile} is not a subclass of
 414      * {@code InputStream}, this method behaves in exactly the
 415      * same way as the {@link InputStream#read(byte[])} method of
 416      * {@code InputStream}.
 417      *
 418      * @param      b   the buffer into which the data is read.
 419      * @return     the total number of bytes read into the buffer, or
 420      *             {@code -1} if there is no more data because the end of
 421      *             this file has been reached.
 422      * @throws     IOException If the first byte cannot be read for any reason
 423      *             other than end of file, or if the random access file has been closed,
 424      *             or if some other I/O error occurs.
 425      * @throws     NullPointerException If {@code b} is {@code null}.
 426      */
 427     public int read(byte[] b) throws IOException {
 428         return readBytes(b, 0, b.length);
 429     }
 430 
 431     /**
 432      * Reads {@code b.length} bytes from this file into the byte
 433      * array, starting at the current file pointer. This method reads
 434      * repeatedly from the file until the requested number of bytes are
 435      * read. This method blocks until the requested number of bytes are
 436      * read, the end of the stream is detected, or an exception is thrown.
 437      *
 438      * @param   b   the buffer into which the data is read.
 439      * @throws  NullPointerException if {@code b} is {@code null}.
 440      * @throws  EOFException  if this file reaches the end before reading
 441      *              all the bytes.
 442      * @throws  IOException   if an I/O error occurs.
 443      */
 444     public final void readFully(byte[] b) throws IOException {
 445         readFully(b, 0, b.length);
 446     }
 447 
 448     /**
 449      * Reads exactly {@code len} bytes from this file into the byte
 450      * array, starting at the current file pointer. This method reads
 451      * repeatedly from the file until the requested number of bytes are
 452      * read. This method blocks until the requested number of bytes are
 453      * read, the end of the stream is detected, or an exception is thrown.
 454      *
 455      * @param   b     the buffer into which the data is read.
 456      * @param   off   the start offset into the data array {@code b}.
 457      * @param   len   the number of bytes to read.
 458      * @throws  NullPointerException if {@code b} is {@code null}.
 459      * @throws  IndexOutOfBoundsException if {@code off} is negative,
 460      *                {@code len} is negative, or {@code len} is greater than
 461      *                {@code b.length - off}.
 462      * @throws  EOFException  if this file reaches the end before reading
 463      *                all the bytes.
 464      * @throws  IOException   if an I/O error occurs.
 465      */
 466     public final void readFully(byte[] b, int off, int len) throws IOException {
 467         int n = 0;
 468         do {
 469             int count = this.read(b, off + n, len - n);
 470             if (count < 0)
 471                 throw new EOFException();
 472             n += count;
 473         } while (n < len);
 474     }
 475 
 476     /**
 477      * Attempts to skip over {@code n} bytes of input discarding the
 478      * skipped bytes.
 479      * <p>
 480      *
 481      * This method may skip over some smaller number of bytes, possibly zero.
 482      * This may result from any of a number of conditions; reaching end of
 483      * file before {@code n} bytes have been skipped is only one
 484      * possibility. This method never throws an {@code EOFException}.
 485      * The actual number of bytes skipped is returned.  If {@code n}
 486      * is negative, no bytes are skipped.
 487      *
 488      * @param      n   the number of bytes to be skipped.
 489      * @return     the actual number of bytes skipped.
 490      * @throws     IOException  if an I/O error occurs.
 491      */
 492     public int skipBytes(int n) throws IOException {
 493         long pos;
 494         long len;
 495         long newpos;
 496 
 497         if (n <= 0) {
 498             return 0;
 499         }
 500         pos = getFilePointer();
 501         len = length();
 502         newpos = pos + n;
 503         if (newpos > len) {
 504             newpos = len;
 505         }
 506         seek(newpos);
 507 
 508         /* return the actual number of bytes skipped */
 509         return (int) (newpos - pos);
 510     }
 511 
 512     // 'Write' primitives
 513 
 514     /**
 515      * Writes the specified byte to this file. The write starts at
 516      * the current file pointer.
 517      *
 518      * @param      b   the {@code byte} to be written.
 519      * @throws     IOException  if an I/O error occurs.
 520      */
 521     public void write(int b) throws IOException {
 522         write0(b);




 523     }
 524 
 525     private native void write0(int b) throws IOException;
 526 
 527     /**
 528      * Writes a sub array as a sequence of bytes.
 529      *
 530      * @param     b the data to be written
 531      * @param     off the start offset in the data
 532      * @param     len the number of bytes that are written
 533      * @throws    IOException If an I/O error has occurred.
 534      */
 535     private native void writeBytes(byte[] b, int off, int len) throws IOException;








 536 
 537     /**
 538      * Writes {@code b.length} bytes from the specified byte array
 539      * to this file, starting at the current file pointer.
 540      *
 541      * @param      b   the data.
 542      * @throws     IOException  if an I/O error occurs.
 543      */
 544     public void write(byte[] b) throws IOException {
 545         writeBytes(b, 0, b.length);
 546     }
 547 
 548     /**
 549      * Writes {@code len} bytes from the specified byte array
 550      * starting at offset {@code off} to this file.
 551      *
 552      * @param      b     the data.
 553      * @param      off   the start offset in the data.
 554      * @param      len   the number of bytes to write.
 555      * @throws     IOException  if an I/O error occurs.
 556      * @throws     IndexOutOfBoundsException {@inheritDoc}
 557      */
 558     public void write(byte[] b, int off, int len) throws IOException {
 559         writeBytes(b, off, len);
 560     }
 561 
 562     // 'Random access' stuff
 563 
 564     /**
 565      * Returns the current offset in this file.
 566      *
 567      * @return     the offset from the beginning of the file, in bytes,
 568      *             at which the next read or write occurs.
 569      * @throws     IOException  if an I/O error occurs.
 570      */
 571     public native long getFilePointer() throws IOException;
 572 
 573     /**
 574      * Sets the file-pointer offset, measured from the beginning of this
 575      * file, at which the next read or write occurs.  The offset may be
 576      * set beyond the end of the file. Setting the offset beyond the end
 577      * of the file does not change the file length.  The file length will
 578      * change only by writing after the offset has been set beyond the end
 579      * of the file.
 580      *
 581      * @param      pos   the offset position, measured in bytes from the
 582      *                   beginning of the file, at which to set the file
 583      *                   pointer.
 584      * @throws     IOException  if {@code pos} is less than
 585      *                          {@code 0} or if an I/O error occurs.
 586      */
 587     public void seek(long pos) throws IOException {
 588         if (pos < 0) {
 589             throw new IOException("Negative seek offset");



 590         } else {
 591             seek0(pos);
 592         }
 593     }
 594 
 595     private native void seek0(long pos) throws IOException;
 596 
 597     /**
 598      * Returns the length of this file.
 599      *
 600      * @return     the length of this file, measured in bytes.
 601      * @throws     IOException  if an I/O error occurs.
 602      */
 603     public native long length() throws IOException;








 604 
 605     /**
 606      * Sets the length of this file.
 607      *
 608      * <p> If the present length of the file as returned by the
 609      * {@code length} method is greater than the {@code newLength}
 610      * argument then the file will be truncated.  In this case, if the file
 611      * offset as returned by the {@code getFilePointer} method is greater
 612      * than {@code newLength} then after this method returns the offset
 613      * will be equal to {@code newLength}.
 614      *
 615      * <p> If the present length of the file as returned by the
 616      * {@code length} method is smaller than the {@code newLength}
 617      * argument then the file will be extended.  In this case, the contents of
 618      * the extended portion of the file are not defined.
 619      *
 620      * @param      newLength    The desired length of the file
 621      * @throws     IOException  If an I/O error occurs
 622      * @since      1.2
 623      */
 624     public native void setLength(long newLength) throws IOException;








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