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 native void open0(String name, int mode)
 300         throws FileNotFoundException;
 301 
 302     // wrap native call to allow instrumentation
 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 void open(String name, int mode)
 315         throws FileNotFoundException {
 316         open0(name, mode);
 317     }
 318 
 319     // 'Read' primitives
 320 
 321     /**
 322      * Reads a byte of data from this file. The byte is returned as an
 323      * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This
 324      * method blocks if no input is yet available.
 325      * <p>
 326      * Although {@code RandomAccessFile} is not a subclass of
 327      * {@code InputStream}, this method behaves in exactly the same
 328      * way as the {@link InputStream#read()} method of
 329      * {@code InputStream}.
 330      *
 331      * @return     the next byte of data, or {@code -1} if the end of the
 332      *             file has been reached.
 333      * @exception  IOException  if an I/O error occurs. Not thrown if
 334      *                          end-of-file has been reached.
 335      */
 336     public int read() throws IOException {
 337         return read0();
 338     }
 339 
 340     private native int read0() throws IOException;
 341 
 342     /**
 343      * Reads a sub array as a sequence of bytes.
 344      * @param b the buffer into which the data is read.
 345      * @param off the start offset of the data.
 346      * @param len the number of bytes to read.
 347      * @exception IOException If an I/O error has occurred.
 348      */
 349     private native int readBytes(byte b[], int off, int len) throws IOException;
 350 
 351     /**
 352      * Reads up to {@code len} bytes of data from this file into an
 353      * array of bytes. This method blocks until at least one byte of input
 354      * is available.
 355      * <p>
 356      * Although {@code RandomAccessFile} is not a subclass of
 357      * {@code InputStream}, this method behaves in exactly the
 358      * same way as the {@link InputStream#read(byte[], int, int)} method of
 359      * {@code InputStream}.
 360      *
 361      * @param      b     the buffer into which the data is read.
 362      * @param      off   the start offset in array {@code b}
 363      *                   at which the data is written.
 364      * @param      len   the maximum number of bytes read.
 365      * @return     the total number of bytes read into the buffer, or
 366      *             {@code -1} if there is no more data because the end of
 367      *             the file has been reached.
 368      * @exception  IOException If the first byte cannot be read for any reason
 369      * other than end of file, or if the random access file has been closed, or if
 370      * some other I/O error occurs.
 371      * @exception  NullPointerException If {@code b} is {@code null}.
 372      * @exception  IndexOutOfBoundsException If {@code off} is negative,
 373      * {@code len} is negative, or {@code len} is greater than
 374      * {@code b.length - off}
 375      */
 376     public int read(byte b[], int off, int len) throws IOException {
 377         return readBytes(b, off, len);
 378     }
 379 
 380     /**
 381      * Reads up to {@code b.length} bytes of data from this file
 382      * into an array of bytes. This method blocks until at least one byte
 383      * of input is available.
 384      * <p>
 385      * Although {@code RandomAccessFile} is not a subclass of
 386      * {@code InputStream}, this method behaves in exactly the
 387      * same way as the {@link InputStream#read(byte[])} method of
 388      * {@code InputStream}.
 389      *
 390      * @param      b   the buffer into which the data is read.
 391      * @return     the total number of bytes read into the buffer, or
 392      *             {@code -1} if there is no more data because the end of
 393      *             this file has been reached.
 394      * @exception  IOException If the first byte cannot be read for any reason
 395      * other than end of file, or if the random access file has been closed, or if
 396      * some other I/O error occurs.
 397      * @exception  NullPointerException If {@code b} is {@code null}.
 398      */
 399     public int read(byte b[]) throws IOException {
 400         return readBytes(b, 0, b.length);
 401     }
 402 
 403     /**
 404      * Reads {@code b.length} bytes from this file into the byte
 405      * array, starting at the current file pointer. This method reads
 406      * repeatedly from the file until the requested number of bytes are
 407      * read. This method blocks until the requested number of bytes are
 408      * read, the end of the stream is detected, or an exception is thrown.
 409      *
 410      * @param      b   the buffer into which the data is read.
 411      * @exception  EOFException  if this file reaches the end before reading
 412      *               all the bytes.
 413      * @exception  IOException   if an I/O error occurs.
 414      */
 415     public final void readFully(byte b[]) throws IOException {
 416         readFully(b, 0, b.length);
 417     }
 418 
 419     /**
 420      * Reads exactly {@code len} bytes from this file into the byte
 421      * array, starting at the current file pointer. This method reads
 422      * repeatedly from the file until the requested number of bytes are
 423      * read. This method blocks until the requested number of bytes are
 424      * read, the end of the stream is detected, or an exception is thrown.
 425      *
 426      * @param      b     the buffer into which the data is read.
 427      * @param      off   the start offset of the data.
 428      * @param      len   the number of bytes to read.
 429      * @exception  EOFException  if this file reaches the end before reading
 430      *               all the bytes.
 431      * @exception  IOException   if an I/O error occurs.
 432      */
 433     public final void readFully(byte b[], int off, int len) throws IOException {
 434         int n = 0;
 435         do {
 436             int count = this.read(b, off + n, len - n);
 437             if (count < 0)
 438                 throw new EOFException();
 439             n += count;
 440         } while (n < len);
 441     }
 442 
 443     /**
 444      * Attempts to skip over {@code n} bytes of input discarding the
 445      * skipped bytes.
 446      * <p>
 447      *
 448      * This method may skip over some smaller number of bytes, possibly zero.
 449      * This may result from any of a number of conditions; reaching end of
 450      * file before {@code n} bytes have been skipped is only one
 451      * possibility. This method never throws an {@code EOFException}.
 452      * The actual number of bytes skipped is returned.  If {@code n}
 453      * is negative, no bytes are skipped.
 454      *
 455      * @param      n   the number of bytes to be skipped.
 456      * @return     the actual number of bytes skipped.
 457      * @exception  IOException  if an I/O error occurs.
 458      */
 459     public int skipBytes(int n) throws IOException {
 460         long pos;
 461         long len;
 462         long newpos;
 463 
 464         if (n <= 0) {
 465             return 0;
 466         }
 467         pos = getFilePointer();
 468         len = length();
 469         newpos = pos + n;
 470         if (newpos > len) {
 471             newpos = len;
 472         }
 473         seek(newpos);
 474 
 475         /* return the actual number of bytes skipped */
 476         return (int) (newpos - pos);
 477     }
 478 
 479     // 'Write' primitives
 480 
 481     /**
 482      * Writes the specified byte to this file. The write starts at
 483      * the current file pointer.
 484      *
 485      * @param      b   the {@code byte} to be written.
 486      * @exception  IOException  if an I/O error occurs.
 487      */
 488     public void write(int b) throws IOException {
 489         write0(b);
 490     }
 491 
 492     private native void write0(int b) throws IOException;
 493 
 494     /**
 495      * Writes a sub array as a sequence of bytes.
 496      * @param b the data to be written
 497 
 498      * @param off the start offset in the data
 499      * @param len the number of bytes that are written
 500      * @exception IOException If an I/O error has occurred.
 501      */
 502     private native void writeBytes(byte b[], int off, int len) throws IOException;
 503 
 504     /**
 505      * Writes {@code b.length} bytes from the specified byte array
 506      * to this file, starting at the current file pointer.
 507      *
 508      * @param      b   the data.
 509      * @exception  IOException  if an I/O error occurs.
 510      */
 511     public void write(byte b[]) throws IOException {
 512         writeBytes(b, 0, b.length);
 513     }
 514 
 515     /**
 516      * Writes {@code len} bytes from the specified byte array
 517      * starting at offset {@code off} to this file.
 518      *
 519      * @param      b     the data.
 520      * @param      off   the start offset in the data.
 521      * @param      len   the number of bytes to write.
 522      * @exception  IOException  if an I/O error occurs.
 523      */
 524     public void write(byte b[], int off, int len) throws IOException {
 525         writeBytes(b, off, len);
 526     }
 527 
 528     // 'Random access' stuff
 529 
 530     /**
 531      * Returns the current offset in this file.
 532      *
 533      * @return     the offset from the beginning of the file, in bytes,
 534      *             at which the next read or write occurs.
 535      * @exception  IOException  if an I/O error occurs.
 536      */
 537     public native long getFilePointer() throws IOException;
 538 
 539     /**
 540      * Sets the file-pointer offset, measured from the beginning of this
 541      * file, at which the next read or write occurs.  The offset may be
 542      * set beyond the end of the file. Setting the offset beyond the end
 543      * of the file does not change the file length.  The file length will
 544      * change only by writing after the offset has been set beyond the end
 545      * of the file.
 546      *
 547      * @param      pos   the offset position, measured in bytes from the
 548      *                   beginning of the file, at which to set the file
 549      *                   pointer.
 550      * @exception  IOException  if {@code pos} is less than
 551      *                          {@code 0} or if an I/O error occurs.
 552      */
 553     public void seek(long pos) throws IOException {
 554         if (pos < 0) {
 555             throw new IOException("Negative seek offset");
 556         } else {
 557             seek0(pos);
 558         }
 559     }
 560 
 561     private native void seek0(long pos) throws IOException;
 562 
 563     /**
 564      * Returns the length of this file.
 565      *
 566      * @return     the length of this file, measured in bytes.
 567      * @exception  IOException  if an I/O error occurs.
 568      */
 569     public native long length() throws IOException;
 570 
 571     /**
 572      * Sets the length of this file.
 573      *
 574      * <p> If the present length of the file as returned by the
 575      * {@code length} method is greater than the {@code newLength}
 576      * argument then the file will be truncated.  In this case, if the file
 577      * offset as returned by the {@code getFilePointer} method is greater
 578      * than {@code newLength} then after this method returns the offset
 579      * will be equal to {@code newLength}.
 580      *
 581      * <p> If the present length of the file as returned by the
 582      * {@code length} method is smaller than the {@code newLength}
 583      * argument then the file will be extended.  In this case, the contents of
 584      * the extended portion of the file are not defined.
 585      *
 586      * @param      newLength    The desired length of the file
 587      * @exception  IOException  If an I/O error occurs
 588      * @since      1.2
 589      */
 590     public native void setLength(long newLength) throws IOException;
 591 
 592     /**
 593      * Closes this random access file stream and releases any system
 594      * resources associated with the stream. A closed random access
 595      * file cannot perform input or output operations and cannot be
 596      * reopened.
 597      *
 598      * <p> If this file has an associated channel then the channel is closed
 599      * as well.
 600      *
 601      * @exception  IOException  if an I/O error occurs.
 602      *
 603      * @revised 1.4
 604      * @spec JSR-51
 605      */
 606     public void close() throws IOException {
 607         synchronized (closeLock) {
 608             if (closed) {
 609                 return;
 610             }
 611             closed = true;
 612         }
 613         if (channel != null) {
 614             channel.close();
 615         }
 616 
 617         fd.closeAll(new Closeable() {
 618             public void close() throws IOException {
 619                close0();
 620            }
 621         });
 622     }
 623 
 624     //
 625     //  Some "reading/writing Java data types" methods stolen from
 626     //  DataInputStream and DataOutputStream.
 627     //
 628 
 629     /**
 630      * Reads a {@code boolean} from this file. This method reads a
 631      * single byte from the file, starting at the current file pointer.
 632      * A value of {@code 0} represents
 633      * {@code false}. Any other value represents {@code true}.
 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 {@code boolean} value read.
 638      * @exception  EOFException  if this file has reached the end.
 639      * @exception  IOException   if an I/O error occurs.
 640      */
 641     public final boolean readBoolean() throws IOException {
 642         int ch = this.read();
 643         if (ch < 0)
 644             throw new EOFException();
 645         return (ch != 0);
 646     }
 647 
 648     /**
 649      * Reads a signed eight-bit value from this file. This method reads a
 650      * byte from the file, starting from the current file pointer.
 651      * If the byte read is {@code b}, where
 652      * <code>0&nbsp;&lt;=&nbsp;b&nbsp;&lt;=&nbsp;255</code>,
 653      * then the result is:
 654      * <blockquote><pre>
 655      *     (byte)(b)
 656      * </pre></blockquote>
 657      * <p>
 658      * This method blocks until the byte is read, the end of the stream
 659      * is detected, or an exception is thrown.
 660      *
 661      * @return     the next byte of this file as a signed eight-bit
 662      *             {@code byte}.
 663      * @exception  EOFException  if this file has reached the end.
 664      * @exception  IOException   if an I/O error occurs.
 665      */
 666     public final byte readByte() throws IOException {
 667         int ch = this.read();
 668         if (ch < 0)
 669             throw new EOFException();
 670         return (byte)(ch);
 671     }
 672 
 673     /**
 674      * Reads an unsigned eight-bit number from this file. This method reads
 675      * a byte from this file, starting at the current file pointer,
 676      * and returns that byte.
 677      * <p>
 678      * This method blocks until the byte is read, the end of the stream
 679      * is detected, or an exception is thrown.
 680      *
 681      * @return     the next byte of this file, interpreted as an unsigned
 682      *             eight-bit number.
 683      * @exception  EOFException  if this file has reached the end.
 684      * @exception  IOException   if an I/O error occurs.
 685      */
 686     public final int readUnsignedByte() throws IOException {
 687         int ch = this.read();
 688         if (ch < 0)
 689             throw new EOFException();
 690         return ch;
 691     }
 692 
 693     /**
 694      * Reads a signed 16-bit number from this file. The method reads two
 695      * bytes from this file, starting at the current file pointer.
 696      * If the two bytes read, in order, are
 697      * {@code b1} and {@code b2}, where each of the two values is
 698      * between {@code 0} and {@code 255}, inclusive, then the
 699      * result is equal to:
 700      * <blockquote><pre>
 701      *     (short)((b1 &lt;&lt; 8) | b2)
 702      * </pre></blockquote>
 703      * <p>
 704      * This method blocks until the two bytes are read, the end of the
 705      * stream is detected, or an exception is thrown.
 706      *
 707      * @return     the next two bytes of this file, interpreted as a signed
 708      *             16-bit number.
 709      * @exception  EOFException  if this file reaches the end before reading
 710      *               two bytes.
 711      * @exception  IOException   if an I/O error occurs.
 712      */
 713     public final short readShort() throws IOException {
 714         int ch1 = this.read();
 715         int ch2 = this.read();
 716         if ((ch1 | ch2) < 0)
 717             throw new EOFException();
 718         return (short)((ch1 << 8) + (ch2 << 0));
 719     }
 720 
 721     /**
 722      * Reads an unsigned 16-bit number from this file. This method reads
 723      * two bytes from the file, starting at the current file pointer.
 724      * If the bytes read, in order, are
 725      * {@code b1} and {@code b2}, where
 726      * <code>0&nbsp;&lt;=&nbsp;b1, b2&nbsp;&lt;=&nbsp;255</code>,
 727      * then the result is equal to:
 728      * <blockquote><pre>
 729      *     (b1 &lt;&lt; 8) | b2
 730      * </pre></blockquote>
 731      * <p>
 732      * This method blocks until the two bytes are read, the end of the
 733      * stream is detected, or an exception is thrown.
 734      *
 735      * @return     the next two bytes of this file, interpreted as an unsigned
 736      *             16-bit integer.
 737      * @exception  EOFException  if this file reaches the end before reading
 738      *               two bytes.
 739      * @exception  IOException   if an I/O error occurs.
 740      */
 741     public final int readUnsignedShort() throws IOException {
 742         int ch1 = this.read();
 743         int ch2 = this.read();
 744         if ((ch1 | ch2) < 0)
 745             throw new EOFException();
 746         return (ch1 << 8) + (ch2 << 0);
 747     }
 748 
 749     /**
 750      * Reads a character from this file. This method reads two
 751      * bytes from the file, starting at the current file pointer.
 752      * If the bytes read, in order, are
 753      * {@code b1} and {@code b2}, where
 754      * <code>0&nbsp;&lt;=&nbsp;b1,&nbsp;b2&nbsp;&lt;=&nbsp;255</code>,
 755      * then the result is equal to:
 756      * <blockquote><pre>
 757      *     (char)((b1 &lt;&lt; 8) | b2)
 758      * </pre></blockquote>
 759      * <p>
 760      * This method blocks until the two bytes are read, the end of the
 761      * stream is detected, or an exception is thrown.
 762      *
 763      * @return     the next two bytes of this file, interpreted as a
 764      *                  {@code char}.
 765      * @exception  EOFException  if this file reaches the end before reading
 766      *               two bytes.
 767      * @exception  IOException   if an I/O error occurs.
 768      */
 769     public final char readChar() throws IOException {
 770         int ch1 = this.read();
 771         int ch2 = this.read();
 772         if ((ch1 | ch2) < 0)
 773             throw new EOFException();
 774         return (char)((ch1 << 8) + (ch2 << 0));
 775     }
 776 
 777     /**
 778      * Reads a signed 32-bit integer from this file. This method reads 4
 779      * bytes from the file, starting at the current file pointer.
 780      * If the bytes read, in order, are {@code b1},
 781      * {@code b2}, {@code b3}, and {@code b4}, where
 782      * <code>0&nbsp;&lt;=&nbsp;b1, b2, b3, b4&nbsp;&lt;=&nbsp;255</code>,
 783      * then the result is equal to:
 784      * <blockquote><pre>
 785      *     (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4
 786      * </pre></blockquote>
 787      * <p>
 788      * This method blocks until the four bytes are read, the end of the
 789      * stream is detected, or an exception is thrown.
 790      *
 791      * @return     the next four bytes of this file, interpreted as an
 792      *             {@code int}.
 793      * @exception  EOFException  if this file reaches the end before reading
 794      *               four bytes.
 795      * @exception  IOException   if an I/O error occurs.
 796      */
 797     public final int readInt() throws IOException {
 798         int ch1 = this.read();
 799         int ch2 = this.read();
 800         int ch3 = this.read();
 801         int ch4 = this.read();
 802         if ((ch1 | ch2 | ch3 | ch4) < 0)
 803             throw new EOFException();
 804         return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
 805     }
 806 
 807     /**
 808      * Reads a signed 64-bit integer from this file. This method reads eight
 809      * bytes from the file, starting at the current file pointer.
 810      * If the bytes read, in order, are
 811      * {@code b1}, {@code b2}, {@code b3},
 812      * {@code b4}, {@code b5}, {@code b6},
 813      * {@code b7}, and {@code b8,} where:
 814      * <blockquote><pre>
 815      *     0 &lt;= b1, b2, b3, b4, b5, b6, b7, b8 &lt;=255,
 816      * </pre></blockquote>
 817      * <p>
 818      * then the result is equal to:
 819      * <blockquote><pre>
 820      *     ((long)b1 &lt;&lt; 56) + ((long)b2 &lt;&lt; 48)
 821      *     + ((long)b3 &lt;&lt; 40) + ((long)b4 &lt;&lt; 32)
 822      *     + ((long)b5 &lt;&lt; 24) + ((long)b6 &lt;&lt; 16)
 823      *     + ((long)b7 &lt;&lt; 8) + b8
 824      * </pre></blockquote>
 825      * <p>
 826      * This method blocks until the eight bytes are read, the end of the
 827      * stream is detected, or an exception is thrown.
 828      *
 829      * @return     the next eight bytes of this file, interpreted as a
 830      *             {@code long}.
 831      * @exception  EOFException  if this file reaches the end before reading
 832      *               eight bytes.
 833      * @exception  IOException   if an I/O error occurs.
 834      */
 835     public final long readLong() throws IOException {
 836         return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
 837     }
 838 
 839     /**
 840      * Reads a {@code float} from this file. This method reads an
 841      * {@code int} value, starting at the current file pointer,
 842      * as if by the {@code readInt} method
 843      * and then converts that {@code int} to a {@code float}
 844      * using the {@code intBitsToFloat} method in class
 845      * {@code Float}.
 846      * <p>
 847      * This method blocks until the four bytes are read, the end of the
 848      * stream is detected, or an exception is thrown.
 849      *
 850      * @return     the next four bytes of this file, interpreted as a
 851      *             {@code float}.
 852      * @exception  EOFException  if this file reaches the end before reading
 853      *             four bytes.
 854      * @exception  IOException   if an I/O error occurs.
 855      * @see        java.io.RandomAccessFile#readInt()
 856      * @see        java.lang.Float#intBitsToFloat(int)
 857      */
 858     public final float readFloat() throws IOException {
 859         return Float.intBitsToFloat(readInt());
 860     }
 861 
 862     /**
 863      * Reads a {@code double} from this file. This method reads a
 864      * {@code long} value, starting at the current file pointer,
 865      * as if by the {@code readLong} method
 866      * and then converts that {@code long} to a {@code double}
 867      * using the {@code longBitsToDouble} method in
 868      * class {@code Double}.
 869      * <p>
 870      * This method blocks until the eight bytes are read, the end of the
 871      * stream is detected, or an exception is thrown.
 872      *
 873      * @return     the next eight bytes of this file, interpreted as a
 874      *             {@code double}.
 875      * @exception  EOFException  if this file reaches the end before reading
 876      *             eight bytes.
 877      * @exception  IOException   if an I/O error occurs.
 878      * @see        java.io.RandomAccessFile#readLong()
 879      * @see        java.lang.Double#longBitsToDouble(long)
 880      */
 881     public final double readDouble() throws IOException {
 882         return Double.longBitsToDouble(readLong());
 883     }
 884 
 885     /**
 886      * Reads the next line of text from this file.  This method successively
 887      * reads bytes from the file, starting at the current file pointer,
 888      * until it reaches a line terminator or the end
 889      * of the file.  Each byte is converted into a character by taking the
 890      * byte's value for the lower eight bits of the character and setting the
 891      * high eight bits of the character to zero.  This method does not,
 892      * therefore, support the full Unicode character set.
 893      *
 894      * <p> A line of text is terminated by a carriage-return character
 895      * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a
 896      * carriage-return character immediately followed by a newline character,
 897      * or the end of the file.  Line-terminating characters are discarded and
 898      * are not included as part of the string returned.
 899      *
 900      * <p> This method blocks until a newline character is read, a carriage
 901      * return and the byte following it are read (to see if it is a newline),
 902      * the end of the file is reached, or an exception is thrown.
 903      *
 904      * @return     the next line of text from this file, or null if end
 905      *             of file is encountered before even one byte is read.
 906      * @exception  IOException  if an I/O error occurs.
 907      */
 908 
 909     public final String readLine() throws IOException {
 910         StringBuilder input = new StringBuilder();
 911         int c = -1;
 912         boolean eol = false;
 913 
 914         while (!eol) {
 915             switch (c = read()) {
 916             case -1:
 917             case '\n':
 918                 eol = true;
 919                 break;
 920             case '\r':
 921                 eol = true;
 922                 long cur = getFilePointer();
 923                 if ((read()) != '\n') {
 924                     seek(cur);
 925                 }
 926                 break;
 927             default:
 928                 input.append((char)c);
 929                 break;
 930             }
 931         }
 932 
 933         if ((c == -1) && (input.length() == 0)) {
 934             return null;
 935         }
 936         return input.toString();
 937     }
 938 
 939     /**
 940      * Reads in a string from this file. The string has been encoded
 941      * using a
 942      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
 943      * format.
 944      * <p>
 945      * The first two bytes are read, starting from the current file
 946      * pointer, as if by
 947      * {@code readUnsignedShort}. This value gives the number of
 948      * following bytes that are in the encoded string, not
 949      * the length of the resulting string. The following bytes are then
 950      * interpreted as bytes encoding characters in the modified UTF-8 format
 951      * and are converted into characters.
 952      * <p>
 953      * This method blocks until all the bytes are read, the end of the
 954      * stream is detected, or an exception is thrown.
 955      *
 956      * @return     a Unicode string.
 957      * @exception  EOFException            if this file reaches the end before
 958      *               reading all the bytes.
 959      * @exception  IOException             if an I/O error occurs.
 960      * @exception  UTFDataFormatException  if the bytes do not represent
 961      *               valid modified UTF-8 encoding of a Unicode string.
 962      * @see        java.io.RandomAccessFile#readUnsignedShort()
 963      */
 964     public final String readUTF() throws IOException {
 965         return DataInputStream.readUTF(this);
 966     }
 967 
 968     /**
 969      * Writes a {@code boolean} to the file as a one-byte value. The
 970      * value {@code true} is written out as the value
 971      * {@code (byte)1}; the value {@code false} is written out
 972      * as the value {@code (byte)0}. The write starts at
 973      * the current position of the file pointer.
 974      *
 975      * @param      v   a {@code boolean} value to be written.
 976      * @exception  IOException  if an I/O error occurs.
 977      */
 978     public final void writeBoolean(boolean v) throws IOException {
 979         write(v ? 1 : 0);
 980         //written++;
 981     }
 982 
 983     /**
 984      * Writes a {@code byte} to the file as a one-byte value. The
 985      * write starts at the current position of the file pointer.
 986      *
 987      * @param      v   a {@code byte} value to be written.
 988      * @exception  IOException  if an I/O error occurs.
 989      */
 990     public final void writeByte(int v) throws IOException {
 991         write(v);
 992         //written++;
 993     }
 994 
 995     /**
 996      * Writes a {@code short} to the file as two bytes, high byte first.
 997      * The write starts at the current position of the file pointer.
 998      *
 999      * @param      v   a {@code short} to be written.
1000      * @exception  IOException  if an I/O error occurs.
1001      */
1002     public final void writeShort(int v) throws IOException {
1003         write((v >>> 8) & 0xFF);
1004         write((v >>> 0) & 0xFF);
1005         //written += 2;
1006     }
1007 
1008     /**
1009      * Writes a {@code char} to the file as a two-byte value, high
1010      * byte first. The write starts at the current position of the
1011      * file pointer.
1012      *
1013      * @param      v   a {@code char} value to be written.
1014      * @exception  IOException  if an I/O error occurs.
1015      */
1016     public final void writeChar(int v) throws IOException {
1017         write((v >>> 8) & 0xFF);
1018         write((v >>> 0) & 0xFF);
1019         //written += 2;
1020     }
1021 
1022     /**
1023      * Writes an {@code int} to the file as four bytes, high byte first.
1024      * The write starts at the current position of the file pointer.
1025      *
1026      * @param      v   an {@code int} to be written.
1027      * @exception  IOException  if an I/O error occurs.
1028      */
1029     public final void writeInt(int v) throws IOException {
1030         write((v >>> 24) & 0xFF);
1031         write((v >>> 16) & 0xFF);
1032         write((v >>>  8) & 0xFF);
1033         write((v >>>  0) & 0xFF);
1034         //written += 4;
1035     }
1036 
1037     /**
1038      * Writes a {@code long} to the file as eight bytes, high byte first.
1039      * The write starts at the current position of the file pointer.
1040      *
1041      * @param      v   a {@code long} to be written.
1042      * @exception  IOException  if an I/O error occurs.
1043      */
1044     public final void writeLong(long v) throws IOException {
1045         write((int)(v >>> 56) & 0xFF);
1046         write((int)(v >>> 48) & 0xFF);
1047         write((int)(v >>> 40) & 0xFF);
1048         write((int)(v >>> 32) & 0xFF);
1049         write((int)(v >>> 24) & 0xFF);
1050         write((int)(v >>> 16) & 0xFF);
1051         write((int)(v >>>  8) & 0xFF);
1052         write((int)(v >>>  0) & 0xFF);
1053         //written += 8;
1054     }
1055 
1056     /**
1057      * Converts the float argument to an {@code int} using the
1058      * {@code floatToIntBits} method in class {@code Float},
1059      * and then writes that {@code int} value to the file as a
1060      * four-byte quantity, high byte first. The write starts at the
1061      * current position of the file pointer.
1062      *
1063      * @param      v   a {@code float} value to be written.
1064      * @exception  IOException  if an I/O error occurs.
1065      * @see        java.lang.Float#floatToIntBits(float)
1066      */
1067     public final void writeFloat(float v) throws IOException {
1068         writeInt(Float.floatToIntBits(v));
1069     }
1070 
1071     /**
1072      * Converts the double argument to a {@code long} using the
1073      * {@code doubleToLongBits} method in class {@code Double},
1074      * and then writes that {@code long} value to the file as an
1075      * eight-byte quantity, high byte first. The write starts at the current
1076      * position of the file pointer.
1077      *
1078      * @param      v   a {@code double} value to be written.
1079      * @exception  IOException  if an I/O error occurs.
1080      * @see        java.lang.Double#doubleToLongBits(double)
1081      */
1082     public final void writeDouble(double v) throws IOException {
1083         writeLong(Double.doubleToLongBits(v));
1084     }
1085 
1086     /**
1087      * Writes the string to the file as a sequence of bytes. Each
1088      * character in the string is written out, in sequence, by discarding
1089      * its high eight bits. The write starts at the current position of
1090      * the file pointer.
1091      *
1092      * @param      s   a string of bytes to be written.
1093      * @exception  IOException  if an I/O error occurs.
1094      */
1095     @SuppressWarnings("deprecation")
1096     public final void writeBytes(String s) throws IOException {
1097         int len = s.length();
1098         byte[] b = new byte[len];
1099         s.getBytes(0, len, b, 0);
1100         writeBytes(b, 0, len);
1101     }
1102 
1103     /**
1104      * Writes a string to the file as a sequence of characters. Each
1105      * character is written to the data output stream as if by the
1106      * {@code writeChar} method. The write starts at the current
1107      * position of the file pointer.
1108      *
1109      * @param      s   a {@code String} value to be written.
1110      * @exception  IOException  if an I/O error occurs.
1111      * @see        java.io.RandomAccessFile#writeChar(int)
1112      */
1113     public final void writeChars(String s) throws IOException {
1114         int clen = s.length();
1115         int blen = 2*clen;
1116         byte[] b = new byte[blen];
1117         char[] c = new char[clen];
1118         s.getChars(0, clen, c, 0);
1119         for (int i = 0, j = 0; i < clen; i++) {
1120             b[j++] = (byte)(c[i] >>> 8);
1121             b[j++] = (byte)(c[i] >>> 0);
1122         }
1123         writeBytes(b, 0, blen);
1124     }
1125 
1126     /**
1127      * Writes a string to the file using
1128      * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1129      * encoding in a machine-independent manner.
1130      * <p>
1131      * First, two bytes are written to the file, starting at the
1132      * current file pointer, as if by the
1133      * {@code writeShort} method giving the number of bytes to
1134      * follow. This value is the number of bytes actually written out,
1135      * not the length of the string. Following the length, each character
1136      * of the string is output, in sequence, using the modified UTF-8 encoding
1137      * for each character.
1138      *
1139      * @param      str   a string to be written.
1140      * @exception  IOException  if an I/O error occurs.
1141      */
1142     public final void writeUTF(String str) throws IOException {
1143         DataOutputStream.writeUTF(str, this);
1144     }
1145 
1146     private static native void initIDs();
1147 
1148     private native void close0() throws IOException;
1149 
1150     static {
1151         initIDs();
1152     }
1153 }