Java Reference
In-Depth Information
RandomAccessFile . A large case study of using RandomAccessFile to organize an
address book is given in Supplement VI.B.
L ISTING 19.8 TestRandomAccessFile.java
1 import java.io.*;
2
3 public class TestRandomAccessFile {
4
public static void main(String[] args) throws IOException {
5
// Create a random-access file
6
7
8
RandomAccessFile inout = new RandomAccessFile( "inout.dat" , "rw" );
RandomAccessFile
// Clear the file to destroy the old contents, if any
9
10
11
inout.setLength( 0 );
empty file
// Write new integers to the file
12
for ( int i = 0 ; i < 200 ; i++)
13
14
15 // Display the current length of the file
16 System.out.println( "Current file length is " +
inout.writeInt(i);
write
inout.length()
);
17
18 // Retrieve the first number
19 // Move the file pointer to the beginning
20 System.out.println( "The first number is " +
inout.seek( 0 );
move pointer
read
inout.readInt()
);
21
22 // Retrieve the second number
23 // Move the file pointer to the second number
24 System.out.println( "The second number is " +
inout.seek( 1 * 4 );
inout.readInt()
);
25
26 // Retrieve the tenth number
27 // Move the file pointer to the tenth number
28 System.out.println( "The tenth number is " +
inout.seek( 9 * 4 );
inout.readInt()
);
29
30
// Modify the eleventh number
31
32
33
inout.writeInt( 555 );
// Append a new number
34
inout.seek(inout.length());
// Move the file pointer to the end
35
36
37 // Display the new length
38 System.out.println( "The new length is " +
inout.writeInt( 999 );
inout.length()
);
39
40 // Retrieve the new eleventh number
41 // Move the file pointer to the next number
42 System.out.println( "The eleventh number is " +
inout.seek( 10 * 4 );
inout.readInt()
);
43
44 inout.close();
45 }
46 }
close file
Current file length is 800
The first number is 0
The second number is 1
The tenth number is 9
The new length is 804
The eleventh number is 555
 
Search WWH ::




Custom Search