KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > io > RandomAccessFile


1 /*
2  * @(#)RandomAccessFile.java 1.78 04/05/13
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.io;
9
10 import java.nio.channels.FileChannel JavaDoc;
11 import sun.nio.ch.FileChannelImpl;
12
13
14 /**
15  * Instances of this class support both reading and writing to a
16  * random access file. A random access file behaves like a large
17  * array of bytes stored in the file system. There is a kind of cursor,
18  * or index into the implied array, called the <em>file pointer</em>;
19  * input operations read bytes starting at the file pointer and advance
20  * the file pointer past the bytes read. If the random access file is
21  * created in read/write mode, then output operations are also available;
22  * output operations write bytes starting at the file pointer and advance
23  * the file pointer past the bytes written. Output operations that write
24  * past the current end of the implied array cause the array to be
25  * extended. The file pointer can be read by the
26  * <code>getFilePointer</code> method and set by the <code>seek</code>
27  * method.
28  * <p>
29  * It is generally true of all the reading routines in this class that
30  * if end-of-file is reached before the desired number of bytes has been
31  * read, an <code>EOFException</code> (which is a kind of
32  * <code>IOException</code>) is thrown. If any byte cannot be read for
33  * any reason other than end-of-file, an <code>IOException</code> other
34  * than <code>EOFException</code> is thrown. In particular, an
35  * <code>IOException</code> may be thrown if the stream has been closed.
36  *
37  * @author unascribed
38  * @version 1.78, 05/13/04
39  * @since JDK1.0
40  */

41
42 public class RandomAccessFile implements DataOutput JavaDoc, DataInput JavaDoc, Closeable JavaDoc {
43
44     private FileDescriptor JavaDoc fd;
45     private FileChannel JavaDoc channel = null;
46     private boolean rw;
47
48     private static final int O_RDONLY = 1;
49     private static final int O_RDWR = 2;
50     private static final int O_SYNC = 4;
51     private static final int O_DSYNC = 8;
52
53     /**
54      * Creates a random access file stream to read from, and optionally
55      * to write to, a file with the specified name. A new
56      * {@link FileDescriptor} object is created to represent the
57      * connection to the file.
58      *
59      * <p> The <tt>mode</tt> argument specifies the access mode with which the
60      * file is to be opened. The permitted values and their meanings are as
61      * specified for the <a
62      * HREF="#mode"><tt>RandomAccessFile(File,String)</tt></a> constructor.
63      *
64      * <p>
65      * If there is a security manager, its <code>checkRead</code> method
66      * is called with the <code>name</code> argument
67      * as its argument to see if read access to the file is allowed.
68      * If the mode allows writing, the security manager's
69      * <code>checkWrite</code> method
70      * is also called with the <code>name</code> argument
71      * as its argument to see if write access to the file is allowed.
72      *
73      * @param name the system-dependent filename
74      * @param mode the access <a HREF="#mode">mode</a>
75      * @exception IllegalArgumentException if the mode argument is not equal
76      * to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
77      * <tt>"rwd"</tt>
78      * @exception FileNotFoundException
79      * if the mode is <tt>"r"</tt> but the given string does not
80      * denote an existing regular file, or if the mode begins with
81      * <tt>"rw"</tt> but the given string does not denote an
82      * existing, writable regular file and a new regular file of
83      * that name cannot be created, or if some other error occurs
84      * while opening or creating the file
85      * @exception SecurityException if a security manager exists and its
86      * <code>checkRead</code> method denies read access to the file
87      * or the mode is "rw" and the security manager's
88      * <code>checkWrite</code> method denies write access to the file
89      * @see java.lang.SecurityException
90      * @see java.lang.SecurityManager#checkRead(java.lang.String)
91      * @see java.lang.SecurityManager#checkWrite(java.lang.String)
92      * @revised 1.4
93      * @spec JSR-51
94      */

95     public RandomAccessFile(String JavaDoc name, String JavaDoc mode)
96     throws FileNotFoundException JavaDoc
97     {
98         this(name != null ? new File JavaDoc(name) : null, mode);
99     }
100
101     /**
102      * Creates a random access file stream to read from, and optionally to
103      * write to, the file specified by the {@link File} argument. A new {@link
104      * FileDescriptor} object is created to represent this file connection.
105      *
106      * <a name="mode"><p> The <tt>mode</tt> argument specifies the access mode
107      * in which the file is to be opened. The permitted values and their
108      * meanings are:
109      *
110      * <blockquote><table summary="Access mode permitted values and meanings">
111      * <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>
112      * <tr><td valign="top"><tt>"r"</tt></td>
113      * <td> Open for reading only. Invoking any of the <tt>write</tt>
114      * methods of the resulting object will cause an {@link
115      * java.io.IOException} to be thrown. </td></tr>
116      * <tr><td valign="top"><tt>"rw"</tt></td>
117      * <td> Open for reading and writing. If the file does not already
118      * exist then an attempt will be made to create it. </td></tr>
119      * <tr><td valign="top"><tt>"rws"</tt></td>
120      * <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
121      * require that every update to the file's content or metadata be
122      * written synchronously to the underlying storage device. </td></tr>
123      * <tr><td valign="top"><tt>"rwd"&nbsp;&nbsp;</tt></td>
124      * <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
125      * require that every update to the file's content be written
126      * synchronously to the underlying storage device. </td></tr>
127      * </table></blockquote>
128      *
129      * The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link
130      * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of
131      * the {@link java.nio.channels.FileChannel} class, passing arguments of
132      * <tt>true</tt> and <tt>false</tt>, respectively, except that they always
133      * apply to every I/O operation and are therefore often more efficient. If
134      * the file resides on a local storage device then when an invocation of a
135      * method of this class returns it is guaranteed that all changes made to
136      * the file by that invocation will have been written to that device. This
137      * is useful for ensuring that critical information is not lost in the
138      * event of a system crash. If the file does not reside on a local device
139      * then no such guarantee is made.
140      *
141      * <p> The <tt>"rwd"</tt> mode can be used to reduce the number of I/O
142      * operations performed. Using <tt>"rwd"</tt> only requires updates to the
143      * file's content to be written to storage; using <tt>"rws"</tt> requires
144      * updates to both the file's content and its metadata to be written, which
145      * generally requires at least one more low-level I/O operation.
146      *
147      * <p> If there is a security manager, its <code>checkRead</code> method is
148      * called with the pathname of the <code>file</code> argument as its
149      * argument to see if read access to the file is allowed. If the mode
150      * allows writing, the security manager's <code>checkWrite</code> method is
151      * also called with the path argument to see if write access to the file is
152      * allowed.
153      *
154      * @param file the file object
155      * @param mode the access mode, as described
156      * <a HREF="#mode">above</a>
157      * @exception IllegalArgumentException if the mode argument is not equal
158      * to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
159      * <tt>"rwd"</tt>
160      * @exception FileNotFoundException
161      * if the mode is <tt>"r"</tt> but the given file object does
162      * not denote an existing regular file, or if the mode begins
163      * with <tt>"rw"</tt> but the given file object does not denote
164      * an existing, writable regular file and a new regular file of
165      * that name cannot be created, or if some other error occurs
166      * while opening or creating the file
167      * @exception SecurityException if a security manager exists and its
168      * <code>checkRead</code> method denies read access to the file
169      * or the mode is "rw" and the security manager's
170      * <code>checkWrite</code> method denies write access to the file
171      * @see java.lang.SecurityManager#checkRead(java.lang.String)
172      * @see java.lang.SecurityManager#checkWrite(java.lang.String)
173      * @see java.nio.channels.FileChannel#force(boolean)
174      * @revised 1.4
175      * @spec JSR-51
176      */

177     public RandomAccessFile(File JavaDoc file, String JavaDoc mode)
178     throws FileNotFoundException JavaDoc
179     {
180     String JavaDoc name = (file != null ? file.getPath() : null);
181     int imode = -1;
182     if (mode.equals("r"))
183         imode = O_RDONLY;
184     else if (mode.startsWith("rw")) {
185         imode = O_RDWR;
186         rw = true;
187         if (mode.length() > 2) {
188         if (mode.equals("rws"))
189             imode |= O_SYNC;
190         else if (mode.equals("rwd"))
191             imode |= O_DSYNC;
192         else
193             imode = -1;
194         }
195     }
196     if (imode < 0)
197         throw new IllegalArgumentException JavaDoc("Illegal mode \"" + mode
198                            + "\" must be one of "
199                            + "\"r\", \"rw\", \"rws\","
200                            + " or \"rwd\"");
201     SecurityManager JavaDoc security = System.getSecurityManager();
202     if (security != null) {
203         security.checkRead(name);
204         if (rw) {
205         security.checkWrite(name);
206         }
207     }
208         if (name == null) {
209             throw new NullPointerException JavaDoc();
210         }
211     fd = new FileDescriptor JavaDoc();
212     open(name, imode);
213     }
214
215     /**
216      * Returns the opaque file descriptor object associated with this
217      * stream. </p>
218      *
219      * @return the file descriptor object associated with this stream.
220      * @exception IOException if an I/O error occurs.
221      * @see java.io.FileDescriptor
222      */

223     public final FileDescriptor JavaDoc getFD() throws IOException JavaDoc {
224     if (fd != null) return fd;
225     throw new IOException JavaDoc();
226     }
227
228     /**
229      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
230      * object associated with this file.
231      *
232      * <p> The {@link java.nio.channels.FileChannel#position()
233      * </code>position<code>} of the returned channel will always be equal to
234      * this object's file-pointer offset as returned by the {@link
235      * #getFilePointer getFilePointer} method. Changing this object's
236      * file-pointer offset, whether explicitly or by reading or writing bytes,
237      * will change the position of the channel, and vice versa. Changing the
238      * file's length via this object will change the length seen via the file
239      * channel, and vice versa.
240      *
241      * @return the file channel associated with this file
242      *
243      * @since 1.4
244      * @spec JSR-51
245      */

246     public final FileChannel JavaDoc getChannel() {
247     synchronized (this) {
248         if (channel == null)
249         channel = FileChannelImpl.open(fd, true, rw, this);
250         return channel;
251     }
252     }
253
254     /**
255      * Opens a file and returns the file descriptor. The file is
256      * opened in read-write mode if the O_RDWR bit in <code>mode</code>
257      * is true, else the file is opened as read-only.
258      * If the <code>name</code> refers to a directory, an IOException
259      * is thrown.
260      *
261      * @param name the name of the file
262      * @param mode the mode flags, a combination of the O_ constants
263      * defined above
264      */

265     private native void open(String JavaDoc name, int mode)
266     throws FileNotFoundException JavaDoc;
267
268     // 'Read' primitives
269

270     /**
271      * Reads a byte of data from this file. The byte is returned as an
272      * integer in the range 0 to 255 (<code>0x00-0x0ff</code>). This
273      * method blocks if no input is yet available.
274      * <p>
275      * Although <code>RandomAccessFile</code> is not a subclass of
276      * <code>InputStream</code>, this method behaves in exactly the same
277      * way as the {@link InputStream#read()} method of
278      * <code>InputStream</code>.
279      *
280      * @return the next byte of data, or <code>-1</code> if the end of the
281      * file has been reached.
282      * @exception IOException if an I/O error occurs. Not thrown if
283      * end-of-file has been reached.
284      */

285     public native int read() throws IOException JavaDoc;
286
287     /**
288      * Reads a sub array as a sequence of bytes.
289      * @param b the buffer into which the data is read.
290      * @param off the start offset of the data.
291      * @param len the number of bytes to read.
292      * @exception IOException If an I/O error has occurred.
293      */

294     private native int readBytes(byte b[], int off, int len) throws IOException JavaDoc;
295
296     /**
297      * Reads up to <code>len</code> bytes of data from this file into an
298      * array of bytes. This method blocks until at least one byte of input
299      * is available.
300      * <p>
301      * Although <code>RandomAccessFile</code> is not a subclass of
302      * <code>InputStream</code>, this method behaves in exactly the
303      * same way as the {@link InputStream#read(byte[], int, int)} method of
304      * <code>InputStream</code>.
305      *
306      * @param b the buffer into which the data is read.
307      * @param off the start offset of the data.
308      * @param len the maximum number of bytes read.
309      * @return the total number of bytes read into the buffer, or
310      * <code>-1</code> if there is no more data because the end of
311      * the file has been reached.
312      * @exception IOException if an I/O error occurs.
313      */

314     public int read(byte b[], int off, int len) throws IOException JavaDoc {
315     return readBytes(b, off, len);
316     }
317
318     /**
319      * Reads up to <code>b.length</code> bytes of data from this file
320      * into an array of bytes. This method blocks until at least one byte
321      * of input is available.
322      * <p>
323      * Although <code>RandomAccessFile</code> is not a subclass of
324      * <code>InputStream</code>, this method behaves in exactly the
325      * same way as the {@link InputStream#read(byte[])} method of
326      * <code>InputStream</code>.
327      *
328      * @param b the buffer into which the data is read.
329      * @return the total number of bytes read into the buffer, or
330      * <code>-1</code> if there is no more data because the end of
331      * this file has been reached.
332      * @exception IOException if an I/O error occurs.
333      */

334     public int read(byte b[]) throws IOException JavaDoc {
335     return readBytes(b, 0, b.length);
336     }
337
338     /**
339      * Reads <code>b.length</code> bytes from this file into the byte
340      * array, starting at the current file pointer. This method reads
341      * repeatedly from the file until the requested number of bytes are
342      * read. This method blocks until the requested number of bytes are
343      * read, the end of the stream is detected, or an exception is thrown.
344      *
345      * @param b the buffer into which the data is read.
346      * @exception EOFException if this file reaches the end before reading
347      * all the bytes.
348      * @exception IOException if an I/O error occurs.
349      */

350     public final void readFully(byte b[]) throws IOException JavaDoc {
351     readFully(b, 0, b.length);
352     }
353
354     /**
355      * Reads exactly <code>len</code> bytes from this file into the byte
356      * array, starting at the current file pointer. This method reads
357      * repeatedly from the file until the requested number of bytes are
358      * read. This method blocks until the requested number of bytes are
359      * read, the end of the stream is detected, or an exception is thrown.
360      *
361      * @param b the buffer into which the data is read.
362      * @param off the start offset of the data.
363      * @param len the number of bytes to read.
364      * @exception EOFException if this file reaches the end before reading
365      * all the bytes.
366      * @exception IOException if an I/O error occurs.
367      */

368     public final void readFully(byte b[], int off, int len) throws IOException JavaDoc {
369         int n = 0;
370     do {
371         int count = this.read(b, off + n, len - n);
372         if (count < 0)
373         throw new EOFException JavaDoc();
374         n += count;
375     } while (n < len);
376     }
377
378     /**
379      * Attempts to skip over <code>n</code> bytes of input discarding the
380      * skipped bytes.
381      * <p>
382      *
383      * This method may skip over some smaller number of bytes, possibly zero.
384      * This may result from any of a number of conditions; reaching end of
385      * file before <code>n</code> bytes have been skipped is only one
386      * possibility. This method never throws an <code>EOFException</code>.
387      * The actual number of bytes skipped is returned. If <code>n</code>
388      * is negative, no bytes are skipped.
389      *
390      * @param n the number of bytes to be skipped.
391      * @return the actual number of bytes skipped.
392      * @exception IOException if an I/O error occurs.
393      */

394     public int skipBytes(int n) throws IOException JavaDoc {
395         long pos;
396     long len;
397     long newpos;
398
399     if (n <= 0) {
400         return 0;
401     }
402     pos = getFilePointer();
403     len = length();
404     newpos = pos + n;
405     if (newpos > len) {
406         newpos = len;
407     }
408     seek(newpos);
409
410     /* return the actual number of bytes skipped */
411     return (int) (newpos - pos);
412     }
413
414     // 'Write' primitives
415

416     /**
417      * Writes the specified byte to this file. The write starts at
418      * the current file pointer.
419      *
420      * @param b the <code>byte</code> to be written.
421      * @exception IOException if an I/O error occurs.
422      */

423     public native void write(int b) throws IOException JavaDoc;
424
425     /**
426      * Writes a sub array as a sequence of bytes.
427      * @param b the data to be written
428
429      * @param off the start offset in the data
430      * @param len the number of bytes that are written
431      * @exception IOException If an I/O error has occurred.
432      */

433     private native void writeBytes(byte b[], int off, int len) throws IOException JavaDoc;
434
435     /**
436      * Writes <code>b.length</code> bytes from the specified byte array
437      * to this file, starting at the current file pointer.
438      *
439      * @param b the data.
440      * @exception IOException if an I/O error occurs.
441      */

442     public void write(byte b[]) throws IOException JavaDoc {
443     writeBytes(b, 0, b.length);
444     }
445
446     /**
447      * Writes <code>len</code> bytes from the specified byte array
448      * starting at offset <code>off</code> to this file.
449      *
450      * @param b the data.
451      * @param off the start offset in the data.
452      * @param len the number of bytes to write.
453      * @exception IOException if an I/O error occurs.
454      */

455     public void write(byte b[], int off, int len) throws IOException JavaDoc {
456     writeBytes(b, off, len);
457     }
458
459     // 'Random access' stuff
460

461     /**
462      * Returns the current offset in this file.
463      *
464      * @return the offset from the beginning of the file, in bytes,
465      * at which the next read or write occurs.
466      * @exception IOException if an I/O error occurs.
467      */

468     public native long getFilePointer() throws IOException JavaDoc;
469
470     /**
471      * Sets the file-pointer offset, measured from the beginning of this
472      * file, at which the next read or write occurs. The offset may be
473      * set beyond the end of the file. Setting the offset beyond the end
474      * of the file does not change the file length. The file length will
475      * change only by writing after the offset has been set beyond the end
476      * of the file.
477      *
478      * @param pos the offset position, measured in bytes from the
479      * beginning of the file, at which to set the file
480      * pointer.
481      * @exception IOException if <code>pos</code> is less than
482      * <code>0</code> or if an I/O error occurs.
483      */

484     public native void seek(long pos) throws IOException JavaDoc;
485
486     /**
487      * Returns the length of this file.
488      *
489      * @return the length of this file, measured in bytes.
490      * @exception IOException if an I/O error occurs.
491      */

492     public native long length() throws IOException JavaDoc;
493
494     /**
495      * Sets the length of this file.
496      *
497      * <p> If the present length of the file as returned by the
498      * <code>length</code> method is greater than the <code>newLength</code>
499      * argument then the file will be truncated. In this case, if the file
500      * offset as returned by the <code>getFilePointer</code> method is greater
501      * than <code>newLength</code> then after this method returns the offset
502      * will be equal to <code>newLength</code>.
503      *
504      * <p> If the present length of the file as returned by the
505      * <code>length</code> method is smaller than the <code>newLength</code>
506      * argument then the file will be extended. In this case, the contents of
507      * the extended portion of the file are not defined.
508      *
509      * @param newLength The desired length of the file
510      * @exception IOException If an I/O error occurs
511      * @since 1.2
512      */

513     public native void setLength(long newLength) throws IOException JavaDoc;
514
515     /**
516      * Closes this random access file stream and releases any system
517      * resources associated with the stream. A closed random access
518      * file cannot perform input or output operations and cannot be
519      * reopened.
520      *
521      * <p> If this file has an associated channel then the channel is closed
522      * as well.
523      *
524      * @exception IOException if an I/O error occurs.
525      *
526      * @revised 1.4
527      * @spec JSR-51
528      */

529     public void close() throws IOException JavaDoc {
530         if (channel != null)
531             channel.close();
532         close0();
533     }
534
535     //
536
// Some "reading/writing Java data types" methods stolen from
537
// DataInputStream and DataOutputStream.
538
//
539

540     /**
541      * Reads a <code>boolean</code> from this file. This method reads a
542      * single byte from the file, starting at the current file pointer.
543      * A value of <code>0</code> represents
544      * <code>false</code>. Any other value represents <code>true</code>.
545      * This method blocks until the byte is read, the end of the stream
546      * is detected, or an exception is thrown.
547      *
548      * @return the <code>boolean</code> value read.
549      * @exception EOFException if this file has reached the end.
550      * @exception IOException if an I/O error occurs.
551      */

552     public final boolean readBoolean() throws IOException JavaDoc {
553     int ch = this.read();
554     if (ch < 0)
555         throw new EOFException JavaDoc();
556     return (ch != 0);
557     }
558
559     /**
560      * Reads a signed eight-bit value from this file. This method reads a
561      * byte from the file, starting from the current file pointer.
562      * If the byte read is <code>b</code>, where
563      * <code>0&nbsp;&lt;=&nbsp;b&nbsp;&lt;=&nbsp;255</code>,
564      * then the result is:
565      * <blockquote><pre>
566      * (byte)(b)
567      * </pre></blockquote>
568      * <p>
569      * This method blocks until the byte is read, the end of the stream
570      * is detected, or an exception is thrown.
571      *
572      * @return the next byte of this file as a signed eight-bit
573      * <code>byte</code>.
574      * @exception EOFException if this file has reached the end.
575      * @exception IOException if an I/O error occurs.
576      */

577     public final byte readByte() throws IOException JavaDoc {
578     int ch = this.read();
579     if (ch < 0)
580         throw new EOFException JavaDoc();
581     return (byte)(ch);
582     }
583
584     /**
585      * Reads an unsigned eight-bit number from this file. This method reads
586      * a byte from this file, starting at the current file pointer,
587      * and returns that byte.
588      * <p>
589      * This method blocks until the byte is read, the end of the stream
590      * is detected, or an exception is thrown.
591      *
592      * @return the next byte of this file, interpreted as an unsigned
593      * eight-bit number.
594      * @exception EOFException if this file has reached the end.
595      * @exception IOException if an I/O error occurs.
596      */

597     public final int readUnsignedByte() throws IOException JavaDoc {
598     int ch = this.read();
599     if (ch < 0)
600         throw new EOFException JavaDoc();
601     return ch;
602     }
603
604     /**
605      * Reads a signed 16-bit number from this file. The method reads two
606      * bytes from this file, starting at the current file pointer.
607      * If the two bytes read, in order, are
608      * <code>b1</code> and <code>b2</code>, where each of the two values is
609      * between <code>0</code> and <code>255</code>, inclusive, then the
610      * result is equal to:
611      * <blockquote><pre>
612      * (short)((b1 &lt;&lt; 8) | b2)
613      * </pre></blockquote>
614      * <p>
615      * This method blocks until the two bytes are read, the end of the
616      * stream is detected, or an exception is thrown.
617      *
618      * @return the next two bytes of this file, interpreted as a signed
619      * 16-bit number.
620      * @exception EOFException if this file reaches the end before reading
621      * two bytes.
622      * @exception IOException if an I/O error occurs.
623      */

624     public final short readShort() throws IOException JavaDoc {
625     int ch1 = this.read();
626     int ch2 = this.read();
627     if ((ch1 | ch2) < 0)
628         throw new EOFException JavaDoc();
629     return (short)((ch1 << 8) + (ch2 << 0));
630     }
631
632     /**
633      * Reads an unsigned 16-bit number from this file. This method reads
634      * two bytes from the file, starting at the current file pointer.
635      * If the bytes read, in order, are
636      * <code>b1</code> and <code>b2</code>, where
637      * <code>0&nbsp;&lt;=&nbsp;b1, b2&nbsp;&lt;=&nbsp;255</code>,
638      * then the result is equal to:
639      * <blockquote><pre>
640      * (b1 &lt;&lt; 8) | b2
641      * </pre></blockquote>
642      * <p>
643      * This method blocks until the two bytes are read, the end of the
644      * stream is detected, or an exception is thrown.
645      *
646      * @return the next two bytes of this file, interpreted as an unsigned
647      * 16-bit integer.
648      * @exception EOFException if this file reaches the end before reading
649      * two bytes.
650      * @exception IOException if an I/O error occurs.
651      */

652     public final int readUnsignedShort() throws IOException JavaDoc {
653     int ch1 = this.read();
654     int ch2 = this.read();
655     if ((ch1 | ch2) < 0)
656         throw new EOFException JavaDoc();
657     return (ch1 << 8) + (ch2 << 0);
658     }
659
660     /**
661      * Reads a Unicode character from this file. This method reads two
662      * bytes from the file, starting at the current file pointer.
663      * If the bytes read, in order, are
664      * <code>b1</code> and <code>b2</code>, where
665      * <code>0&nbsp;&lt;=&nbsp;b1,&nbsp;b2&nbsp;&lt;=&nbsp;255</code>,
666      * then the result is equal to:
667      * <blockquote><pre>
668      * (char)((b1 &lt;&lt; 8) | b2)
669      * </pre></blockquote>
670      * <p>
671      * This method blocks until the two bytes are read, the end of the
672      * stream is detected, or an exception is thrown.
673      *
674      * @return the next two bytes of this file as a Unicode character.
675      * @exception EOFException if this file reaches the end before reading
676      * two bytes.
677      * @exception IOException if an I/O error occurs.
678      */

679     public final char readChar() throws IOException JavaDoc {
680     int ch1 = this.read();
681     int ch2 = this.read();
682     if ((ch1 | ch2) < 0)
683         throw new EOFException JavaDoc();
684     return (char)((ch1 << 8) + (ch2 << 0));
685     }
686
687     /**
688      * Reads a signed 32-bit integer from this file. This method reads 4
689      * bytes from the file, starting at the current file pointer.
690      * If the bytes read, in order, are <code>b1</code>,
691      * <code>b2</code>, <code>b3</code>, and <code>b4</code>, where
692      * <code>0&nbsp;&lt;=&nbsp;b1, b2, b3, b4&nbsp;&lt;=&nbsp;255</code>,
693      * then the result is equal to:
694      * <blockquote><pre>
695      * (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4
696      * </pre></blockquote>
697      * <p>
698      * This method blocks until the four bytes are read, the end of the
699      * stream is detected, or an exception is thrown.
700      *
701      * @return the next four bytes of this file, interpreted as an
702      * <code>int</code>.
703      * @exception EOFException if this file reaches the end before reading
704      * four bytes.
705      * @exception IOException if an I/O error occurs.
706      */

707     public final int readInt() throws IOException JavaDoc {
708     int ch1 = this.read();
709     int ch2 = this.read();
710     int ch3 = this.read();
711     int ch4 = this.read();
712     if ((ch1 | ch2 | ch3 | ch4) < 0)
713         throw new EOFException JavaDoc();
714     return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
715     }
716
717     /**
718      * Reads a signed 64-bit integer from this file. This method reads eight
719      * bytes from the file, starting at the current file pointer.
720      * If the bytes read, in order, are
721      * <code>b1</code>, <code>b2</code>, <code>b3</code>,
722      * <code>b4</code>, <code>b5</code>, <code>b6</code>,
723      * <code>b7</code>, and <code>b8,</code> where:
724      * <blockquote><pre>
725      * 0 &lt;= b1, b2, b3, b4, b5, b6, b7, b8 &lt;=255,
726      * </pre></blockquote>
727      * <p>
728      * then the result is equal to:
729      * <p><blockquote><pre>
730      * ((long)b1 &lt;&lt; 56) + ((long)b2 &lt;&lt; 48)
731      * + ((long)b3 &lt;&lt; 40) + ((long)b4 &lt;&lt; 32)
732      * + ((long)b5 &lt;&lt; 24) + ((long)b6 &lt;&lt; 16)
733      * + ((long)b7 &lt;&lt; 8) + b8
734      * </pre></blockquote>
735      * <p>
736      * This method blocks until the eight bytes are read, the end of the
737      * stream is detected, or an exception is thrown.
738      *
739      * @return the next eight bytes of this file, interpreted as a
740      * <code>long</code>.
741      * @exception EOFException if this file reaches the end before reading
742      * eight bytes.
743      * @exception IOException if an I/O error occurs.
744      */

745     public final long readLong() throws IOException JavaDoc {
746     return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
747     }
748
749     /**
750      * Reads a <code>float</code> from this file. This method reads an
751      * <code>int</code> value, starting at the current file pointer,
752      * as if by the <code>readInt</code> method
753      * and then converts that <code>int</code> to a <code>float</code>
754      * using the <code>intBitsToFloat</code> method in class
755      * <code>Float</code>.
756      * <p>
757      * This method blocks until the four bytes are read, the end of the
758      * stream is detected, or an exception is thrown.
759      *
760      * @return the next four bytes of this file, interpreted as a
761      * <code>float</code>.
762      * @exception EOFException if this file reaches the end before reading
763      * four bytes.
764      * @exception IOException if an I/O error occurs.
765      * @see java.io.RandomAccessFile#readInt()
766      * @see java.lang.Float#intBitsToFloat(int)
767      */

768     public final float readFloat() throws IOException JavaDoc {
769     return Float.intBitsToFloat(readInt());
770     }
771
772     /**
773      * Reads a <code>double</code> from this file. This method reads a
774      * <code>long</code> value, starting at the current file pointer,
775      * as if by the <code>readLong</code> method
776      * and then converts that <code>long</code> to a <code>double</code>
777      * using the <code>longBitsToDouble</code> method in
778      * class <code>Double</code>.
779      * <p>
780      * This method blocks until the eight bytes are read, the end of the
781      * stream is detected, or an exception is thrown.
782      *
783      * @return the next eight bytes of this file, interpreted as a
784      * <code>double</code>.
785      * @exception EOFException if this file reaches the end before reading
786      * eight bytes.
787      * @exception IOException if an I/O error occurs.
788      * @see java.io.RandomAccessFile#readLong()
789      * @see java.lang.Double#longBitsToDouble(long)
790      */

791     public final double readDouble() throws IOException JavaDoc {
792     return Double.longBitsToDouble(readLong());
793     }
794
795     /**
796      * Reads the next line of text from this file. This method successively
797      * reads bytes from the file, starting at the current file pointer,
798      * until it reaches a line terminator or the end
799      * of the file. Each byte is converted into a character by taking the
800      * byte's value for the lower eight bits of the character and setting the
801      * high eight bits of the character to zero. This method does not,
802      * therefore, support the full Unicode character set.
803      *
804      * <p> A line of text is terminated by a carriage-return character
805      * (<code>'&#92;r'</code>), a newline character (<code>'&#92;n'</code>), a
806      * carriage-return character immediately followed by a newline character,
807      * or the end of the file. Line-terminating characters are discarded and
808      * are not included as part of the string returned.
809      *
810      * <p> This method blocks until a newline character is read, a carriage
811      * return and the byte following it are read (to see if it is a newline),
812      * the end of the file is reached, or an exception is thrown.
813      *
814      * @return the next line of text from this file, or null if end
815      * of file is encountered before even one byte is read.
816      * @exception IOException if an I/O error occurs.
817      */

818
819     public final String JavaDoc readLine() throws IOException JavaDoc {
820     StringBuffer JavaDoc input = new StringBuffer JavaDoc();
821     int c = -1;
822     boolean eol = false;
823
824     while (!eol) {
825         switch (c = read()) {
826         case -1:
827         case '\n':
828         eol = true;
829         break;
830         case '\r':
831         eol = true;
832         long cur = getFilePointer();
833         if ((read()) != '\n') {
834             seek(cur);
835         }
836         break;
837         default:
838         input.append((char)c);
839         break;
840         }
841     }
842
843     if ((c == -1) && (input.length() == 0)) {
844         return null;
845     }
846     return input.toString();
847     }
848
849     /**
850      * Reads in a string from this file. The string has been encoded
851      * using a
852      * <a HREF="DataInput.html#modified-utf-8">modified UTF-8</a>
853      * format.
854      * <p>
855      * The first two bytes are read, starting from the current file
856      * pointer, as if by
857      * <code>readUnsignedShort</code>. This value gives the number of
858      * following bytes that are in the encoded string, not
859      * the length of the resulting string. The following bytes are then
860      * interpreted as bytes encoding characters in the modified UTF-8 format
861      * and are converted into characters.
862      * <p>
863      * This method blocks until all the bytes are read, the end of the
864      * stream is detected, or an exception is thrown.
865      *
866      * @return a Unicode string.
867      * @exception EOFException if this file reaches the end before
868      * reading all the bytes.
869      * @exception IOException if an I/O error occurs.
870      * @exception UTFDataFormatException if the bytes do not represent
871      * valid modified UTF-8 encoding of a Unicode string.
872      * @see java.io.RandomAccessFile#readUnsignedShort()
873      */

874     public final String JavaDoc readUTF() throws IOException JavaDoc {
875     return DataInputStream.readUTF(this);
876     }
877
878     /**
879      * Writes a <code>boolean</code> to the file as a one-byte value. The
880      * value <code>true</code> is written out as the value
881      * <code>(byte)1</code>; the value <code>false</code> is written out
882      * as the value <code>(byte)0</code>. The write starts at
883      * the current position of the file pointer.
884      *
885      * @param v a <code>boolean</code> value to be written.
886      * @exception IOException if an I/O error occurs.
887      */

888     public final void writeBoolean(boolean v) throws IOException JavaDoc {
889     write(v ? 1 : 0);
890     //written++;
891
}
892
893     /**
894      * Writes a <code>byte</code> to the file as a one-byte value. The
895      * write starts at the current position of the file pointer.
896      *
897      * @param v a <code>byte</code> value to be written.
898      * @exception IOException if an I/O error occurs.
899      */

900     public final void writeByte(int v) throws IOException JavaDoc {
901     write(v);
902     //written++;
903
}
904
905     /**
906      * Writes a <code>short</code> to the file as two bytes, high byte first.
907      * The write starts at the current position of the file pointer.
908      *
909      * @param v a <code>short</code> to be written.
910      * @exception IOException if an I/O error occurs.
911      */

912     public final void writeShort(int v) throws IOException JavaDoc {
913     write((v >>> 8) & 0xFF);
914     write((v >>> 0) & 0xFF);
915     //written += 2;
916
}
917
918     /**
919      * Writes a <code>char</code> to the file as a two-byte value, high
920      * byte first. The write starts at the current position of the
921      * file pointer.
922      *
923      * @param v a <code>char</code> value to be written.
924      * @exception IOException if an I/O error occurs.
925      */

926     public final void writeChar(int v) throws IOException JavaDoc {
927     write((v >>> 8) & 0xFF);
928     write((v >>> 0) & 0xFF);
929     //written += 2;
930
}
931
932     /**
933      * Writes an <code>int</code> to the file as four bytes, high byte first.
934      * The write starts at the current position of the file pointer.
935      *
936      * @param v an <code>int</code> to be written.
937      * @exception IOException if an I/O error occurs.
938      */

939     public final void writeInt(int v) throws IOException JavaDoc {
940     write((v >>> 24) & 0xFF);
941     write((v >>> 16) & 0xFF);
942     write((v >>> 8) & 0xFF);
943     write((v >>> 0) & 0xFF);
944     //written += 4;
945
}
946
947     /**
948      * Writes a <code>long</code> to the file as eight bytes, high byte first.
949      * The write starts at the current position of the file pointer.
950      *
951      * @param v a <code>long</code> to be written.
952      * @exception IOException if an I/O error occurs.
953      */

954     public final void writeLong(long v) throws IOException JavaDoc {
955     write((int)(v >>> 56) & 0xFF);
956     write((int)(v >>> 48) & 0xFF);
957     write((int)(v >>> 40) & 0xFF);
958     write((int)(v >>> 32) & 0xFF);
959     write((int)(v >>> 24) & 0xFF);
960     write((int)(v >>> 16) & 0xFF);
961     write((int)(v >>> 8) & 0xFF);
962     write((int)(v >>> 0) & 0xFF);
963     //written += 8;
964
}
965
966     /**
967      * Converts the float argument to an <code>int</code> using the
968      * <code>floatToIntBits</code> method in class <code>Float</code>,
969      * and then writes that <code>int</code> value to the file as a
970      * four-byte quantity, high byte first. The write starts at the
971      * current position of the file pointer.
972      *
973      * @param v a <code>float</code> value to be written.
974      * @exception IOException if an I/O error occurs.
975      * @see java.lang.Float#floatToIntBits(float)
976      */

977     public final void writeFloat(float v) throws IOException JavaDoc {
978     writeInt(Float.floatToIntBits(v));
979     }
980
981     /**
982      * Converts the double argument to a <code>long</code> using the
983      * <code>doubleToLongBits</code> method in class <code>Double</code>,
984      * and then writes that <code>long</code> value to the file as an
985      * eight-byte quantity, high byte first. The write starts at the current
986      * position of the file pointer.
987      *
988      * @param v a <code>double</code> value to be written.
989      * @exception IOException if an I/O error occurs.
990      * @see java.lang.Double#doubleToLongBits(double)
991      */

992     public final void writeDouble(double v) throws IOException JavaDoc {
993     writeLong(Double.doubleToLongBits(v));
994     }
995
996     /**
997      * Writes the string to the file as a sequence of bytes. Each
998      * character in the string is written out, in sequence, by discarding
999      * its high eight bits. The write starts at the current position of
1000     * the file pointer.
1001     *
1002     * @param s a string of bytes to be written.
1003     * @exception IOException if an I/O error occurs.
1004     */

1005    public final void writeBytes(String JavaDoc s) throws IOException JavaDoc {
1006    int len = s.length();
1007    byte[] b = new byte[len];
1008    s.getBytes(0, len, b, 0);
1009    writeBytes(b, 0, len);
1010    }
1011
1012    /**
1013     * Writes a string to the file as a sequence of characters. Each
1014     * character is written to the data output stream as if by the
1015     * <code>writeChar</code> method. The write starts at the current
1016     * position of the file pointer.
1017     *
1018     * @param s a <code>String</code> value to be written.
1019     * @exception IOException if an I/O error occurs.
1020     * @see java.io.RandomAccessFile#writeChar(int)
1021     */

1022    public final void writeChars(String JavaDoc s) throws IOException JavaDoc {
1023    int clen = s.length();
1024    int blen = 2*clen;
1025    byte[] b = new byte[blen];
1026    char[] c = new char[clen];
1027    s.getChars(0, clen, c, 0);
1028    for (int i = 0, j = 0; i < clen; i++) {
1029        b[j++] = (byte)(c[i] >>> 8);
1030        b[j++] = (byte)(c[i] >>> 0);
1031    }
1032    writeBytes(b, 0, blen);
1033    }
1034
1035    /**
1036     * Writes a string to the file using
1037     * <a HREF="DataInput.html#modified-utf-8">modified UTF-8</a>
1038     * encoding in a machine-independent manner.
1039     * <p>
1040     * First, two bytes are written to the file, starting at the
1041     * current file pointer, as if by the
1042     * <code>writeShort</code> method giving the number of bytes to
1043     * follow. This value is the number of bytes actually written out,
1044     * not the length of the string. Following the length, each character
1045     * of the string is output, in sequence, using the modified UTF-8 encoding
1046     * for each character.
1047     *
1048     * @param str a string to be written.
1049     * @exception IOException if an I/O error occurs.
1050     */

1051    public final void writeUTF(String JavaDoc str) throws IOException JavaDoc {
1052        DataOutputStream.writeUTF(str, this);
1053    }
1054
1055    private static native void initIDs();
1056
1057    private native void close0() throws IOException JavaDoc;
1058
1059    static {
1060    initIDs();
1061    }
1062
1063}
1064
Popular Tags