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