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