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