Java Reference
In-Depth Information
A
RandomAccessFile
is created for the file named
inout.dat
with mode
rw
to allow both
read and write operations in line 6.
inout.setLength(0)
sets the length to
0
in line 9. This, in effect, destroys the old con-
tents of the file.
The
for
loop writes
200 int
values from
0
to
199
into the file in lines 12 and 13. Since
each
int
value takes
4
bytes, the total length of the file returned from
inout.length()
is
now
800
(line 16), as shown in the sample output.
Invoking
inout.seek(0)
in line 19 sets the file pointer to the beginning of the file.
inout.readInt()
reads the first value in line 20 and moves the file pointer to the next
number. The second number is read in line 24.
inout.seek(9 * 4)
(line 27) moves the file pointer to the tenth number.
inout.readInt()
reads the tenth number and moves the file pointer to the eleventh num-
ber in line 28.
inout.write(555)
writes a new eleventh number at the current position
(line 31). The previous eleventh number is destroyed.
inout.seek(inout.length())
moves the file pointer to the end of the file (line 34).
inout.writeInt(999)
writes a
999
to the file (line 35). Now the length of the file is
increased by
4
, so
inout.length()
returns
804
(line 38).
inout.seek(10 * 4)
moves the file pointer to the eleventh number in line 41. The new
eleventh number,
555
, is displayed in line 42.
17.31
✓
✓
Can
RandomAccessFile
streams read and write a data file created by
DataOutputStream
? Can
RandomAccessFile
streams read and write objects?
Check
Point
17.32
Create a
RandomAccessFile
stream for the file
address.dat
to allow the updating
of student information in the file. Create a
DataOutputStream
for the file
address.dat
. Explain the differences between these two statements.
17.33
What happens if the file
test.dat
does not exist when you attempt to compile and run
the following code?
import
java.io.*;
public class
Test {
public static void
main(String[] args) {
try
( RandomAccessFile raf =
new
RandomAccessFile(
"test.dat"
,
"r"
); ) {
int
i = raf.readInt();
}
catch
(IOException ex) {
System.out.println(
"IO exception"
);
}
}
}
K
EY
T
ERMS
binary I/O 678
deserialization 695
file pointer 698
random-access file
sequential-access file
697
serialization
695
stream
678
697
text I/O
678
Search WWH ::
Custom Search