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