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