public class ReadRandomFile
1: // Fig. 14.28: ReadRandomFile.java
2: // This program reads a random-access file sequentially and
3: // displays the contents one record at a time in text fields.
4: import java.io.EOFException;
5: import java.io.IOException;
6: import java.io.RandomAccessFile;
7:
8: import com.deitel.jhtp6.ch14.RandomAccessAccountRecord;
9:
10: public class ReadRandomFile
11: {
12: private RandomAccessFile input;
13:
14: // enable user to select file to open
15: public void openFile()
16: {
17: try // open file
18: {
19: input = new RandomAccessFile( "clients.dat", "r" );
20: } // end try
21: catch ( IOException ioException )
22: {
23: System.err.println( "File does not exist." );
24: } // end catch
25: } // end method openFile
26:
27: // read and display records
28: public void readRecords()
29: {
30: RandomAccessAccountRecord record = new RandomAccessAccountRecord();
31:
32: System.out.printf( "%-10s%-15s%-15s%10s\n", "Account",
33: "First Name", "Last Name", "Balance" );
34:
35: try // read a record and display
36: {
37: while ( true )
38: {
39: do
40: {
41: record.read( input );
42: } while ( record.getAccount() == 0 );
43:
44: // display record contents
45: System.out.printf( "%-10d%-12s%-12s%10.2f\n",
46: record.getAccount(), record.getFirstName(),
47: record.getLastName(), record.getBalance() );
48: } // end while
49: } // end try
50: catch ( EOFException eofException ) // close file
51: {
52: return; // end of file was reached
53: } // end catch
54: catch ( IOException ioException )
55: {
56: System.err.println( "Error reading file." );
57: System.exit( 1 );
58: } // end catch
59: } // end method readRecords
60:
61: // close file and terminate application
62: public void closeFile()
63: {
64: try // close file and exit
65: {
66: if ( input != null )
67: input.close();
68: } // end try
69: catch ( IOException ioException )
70: {
71: System.err.println( "Error closing file." );
72: System.exit( 1 );
73: } // end catch
74: } // end method closeFile
75: } // end class ReadRandomFile
76:
77: /*************************************************************************
78: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
79: * Pearson Education, Inc. All Rights Reserved. *
80: * *
81: * DISCLAIMER: The authors and publisher of this book have used their *
82: * best efforts in preparing the book. These efforts include the *
83: * development, research, and testing of the theories and programs *
84: * to determine their effectiveness. The authors and publisher make *
85: * no warranty of any kind, expressed or implied, with regard to these *
86: * programs or to the documentation contained in these books. The authors *
87: * and publisher shall not be liable in any event for incidental or *
88: * consequential damages in connection with, or arising out of, the *
89: * furnishing, performance, or use of these programs. *
90: *************************************************************************/