Java Reference
In-Depth Information
«interface»
java.io.DataInput
«interface»
java.io.DataOutput
java.io.RandomAccessFile
+RandomAccessFile(file: File, mode:
String)
+RandomAccessFile(name: String,
mode: String)
+close(): void
+getFilePointer(): long
Creates a RandomAccessFile stream with the specified File object
and mode.
Creates a RandomAccessFile stream with the specified file name
string and mode.
Closes the stream and releases the resource associated with it.
Returns the offset, in bytes, from the beginning of the file to where the
next read or write occurs.
Returns the length of this file.
Reads a byte of data from this file and returns -1 at the end of stream.
Reads up to b.length bytes of data from this file into an array of bytes.
Reads up to len bytes of data from this file into an array of bytes.
Sets the offset (in bytes specified in pos ) from the beginning of the
stream to where the next read or write occurs.
Sets a new length for this file.
Skips over n bytes of input.
Writes b.length bytes from the specified byte array to this file,
starting at the current file pointer.
Writes len bytes from the specified byte array, starting at offset off ,
to this file.
+length(): long
+read(): int
+read(b: byte[]): int
+read(b: byte[], off: int, len: int): int
+seek(pos: long): void
+setLength(newLength: long): void
+skipBytes(int n): int
+write(b: byte[]): void
+write(b: byte[], off: int, len: int):
void
F IGURE 19.17 RandomAccessFile implements the DataInput and DataOutput interfaces with additional methods
to support random access.
Tip
If the file is not intended to be modified, open it with the r mode. This prevents unin-
tentional modification of the file.
A random-access file consists of a sequence of bytes. A special marker called a file pointer is
positioned at one of these bytes. A read or write operation takes place at the location of the file
pointer. When a file is opened, the file pointer is set at the beginning of the file. When you
read or write data to the file, the file pointer moves forward to the next data item. For exam-
ple, if you read an int value using readInt() , the JVM reads 4 bytes from the file pointer,
and now the file pointer is 4 bytes ahead of the previous location, as shown in Figure 19.18.
For a RandomAccessFile raf , you can use the raf.seek(position) method to move
the file pointer to a specified position. raf.seek(0) moves it to the beginning of the file, and
raf.seek(raf.length()) moves it to the end of the file. Listing 19.8 demonstrates
file pointer
File pointer
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
File
byte
byte
(a) Before readInt()
File pointer
(b) After readInt()
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
File
byte
F IGURE 19.18
After an int value is read, the file pointer is moved 4 bytes ahead.
 
 
Search WWH ::




Custom Search