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