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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 16 Files and Streams 939<br />

When the user closes the window, the program attempts <strong>to</strong> add the last record <strong>to</strong> the<br />

file (if there is one in the GUI waiting <strong>to</strong> be output), closes the file and terminates.<br />

16.10 Reading Data Sequentially from a Random-Access File<br />

In the previous sections, we created a random-access file and wrote data <strong>to</strong> that file. In this<br />

section, we develop a program (Fig. 16.14) that opens a RandomAccessFile for reading<br />

with the "r" file open mode, reads through the file sequentially and displays only those<br />

records containing data. This program produces an additional benefit. See whether you can<br />

determine what it is; we will reveal it at the end of this section.<br />

Good <strong>Program</strong>ming Practice 16.1<br />

Open a file with the "r" file open mode for input if the contents of the file should not be modified.<br />

This prevents unintentional modification of the file’s contents. This is another example<br />

of the principle of least privilege. 16.1<br />

1 // Fig. 16.14: ReadRandomFile.java<br />

2 // This program reads a random-access file sequentially and<br />

3 // displays the contents one record at a time in text fields.<br />

4<br />

5 // <strong>Java</strong> core packages<br />

6 import java.awt.*;<br />

7 import java.awt.event.*;<br />

8 import java.io.*;<br />

9 import java.text.DecimalFormat;<br />

10<br />

11 // <strong>Java</strong> extension packages<br />

12 import javax.swing.*;<br />

13<br />

14 // Deitel packages<br />

15 import com.deitel.jhtp4.ch16.*;<br />

16<br />

17 public class ReadRandomFile extends JFrame {<br />

18 private BankUI userInterface;<br />

19 private RandomAccessFile input;<br />

20 private JBut<strong>to</strong>n nextBut<strong>to</strong>n, openBut<strong>to</strong>n;<br />

21<br />

22 // set up GUI<br />

23 public ReadRandomFile()<br />

24 {<br />

25 super( "Read Client File" );<br />

26<br />

27 // create reusable user interface instance<br />

28 userInterface = new BankUI( 4 ); // four textfields<br />

29 getContentPane().add( userInterface );<br />

30<br />

31 // configure generic doTask1 but<strong>to</strong>n from BankUI<br />

32 openBut<strong>to</strong>n = userInterface.getDoTask1But<strong>to</strong>n();<br />

33 openBut<strong>to</strong>n.setText( "Open File for Reading..." );<br />

34<br />

Fig. Fig. 16.14 16.14 Reading a random-access file sequentially (part 1 of 5).

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

Saved successfully!

Ooh no, something went wrong!