26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

920 Files and Streams Chapter 16<br />

Fig. Fig. 16.8 16.8 Reading a sequential file (part 6 of 6).<br />

Most of the code in this example is similar <strong>to</strong> Fig. 16.6, so we discuss only the key lines<br />

of code that are different. Line 105 calls JFileChooser method showOpenDialog <strong>to</strong><br />

display the Open dialog (second screen capture in Fig. 16.8). The behavior and GUI are<br />

the same as the dialog displayed by showSaveDialog, except that the title of the dialog<br />

and the Save but<strong>to</strong>n are both replaced with Open.<br />

Lines 125–126 create a ObjectInputStream object and assign it <strong>to</strong> input. The<br />

File fileName is passed <strong>to</strong> the FileInputStream construc<strong>to</strong>r <strong>to</strong> open the file.<br />

The program reads a record from the file each time the user clicks the Next Record<br />

but<strong>to</strong>n. Line 84 in Next Record’s actionPerformed method calls method<br />

readRecord (lines 144–187) <strong>to</strong> read one record from the file. Line 150 calls method<br />

readObject <strong>to</strong> read an Object from the ObjectInputStream. To use AccountRecord<br />

specific methods, we cast the returned Object <strong>to</strong> type AccountRecord. If<br />

the end-of-file marker is reached during reading, readObject throws an EndOfFile-<br />

Exception.<br />

To retrieve data sequentially from a file, programs normally start reading from the<br />

beginning of the file and read all the data consecutively until the desired data are found. It<br />

might be necessary <strong>to</strong> process the file sequentially several times (from the beginning of the<br />

file) during the execution of a program. Class FileInputStream does not provide the<br />

ability <strong>to</strong> reposition <strong>to</strong> the beginning of the file <strong>to</strong> read the file again unless the program<br />

closes the file and reopens it. Class RandomAccessFile objects can reposition <strong>to</strong> the<br />

beginning of the file. Class RandomAccessFile provides all the capabilities of the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!