img
RandomAccessFile
RandomAccessFile encapsulates a random-access file. It is not derived from InputStream
or OutputStream. Instead, it implements the interfaces DataInput and DataOutput, which
define the basic I/O methods. It also implements the Closeable interface. RandomAccessFile
is special because it supports positioning requests--that is, you can position the file pointer
within the file. It has these two constructors:
RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
RandomAccessFile(String filename, String access)
throws FileNotFoundException
In the first form, fileObj specifies the name of the file to open as a File object. In the second
form, the name of the file is passed in filename. In both cases, access determines what type
of file access is permitted. If it is "r", then the file can be read, but not written. If it is "rw",
then the file is opened in read-write mode. If it is "rws", the file is opened for read-write
operations and every change to the file's data or metadata will be immediately written to
the physical device. If it is "rwd", the file is opened for read-write operations and every
change to the file's data will be immediately written to the physical device.
The method seek( ), shown here, is used to set the current position of the file pointer
within the file:
void seek(long newPos) throws IOException
Here, newPos specifies the new position, in bytes, of the file pointer from the beginning of the
file. After a call to seek( ), the next read or write operation will occur at the new file position.
RandomAccessFile implements the standard input and output methods, which you can
use to read and write to random access files. It also includes some additional methods. One
is setLength( ). It has this signature:
void setLength(long len) throws IOException
This method sets the length of the invoking file to that specified by len. This method can be
used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined.
The Character Streams
While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters. Since one of the main purposes
of Java is to support the "write once, run anywhere" philosophy, it was necessary to include
direct I/O support for characters. In this section, several of the character I/O classes are
discussed. As explained earlier, at the top of the character stream hierarchies are the Reader
and Writer abstract classes. We will begin with them.
NOTE  As discussed in Chapter 13, the character I/O classes were added by the 1.1 release of Java.
OTE
Because of this, you may still find legacy code that uses byte streams where character streams
would be more appropriate. When working on such code, it is a good idea to update it.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home