Java Reference
In-Depth Information
Opening the Data File
Earlier, line 18 (Figure 8-12 on page 499) was entered to declare a variable
named output as a data type of DataOutputStream. The code shown in
Figure 8-20 constructs the instance of this variable.
145
try
146
{
147
output = new DataOutputStream ( new FileOutputStream ( filename )) ;
148
}
149
catch ( IOException io )
150
{
151
JOptionPane.showMessageDialog ( null ,
"The program could not create a storage location. Please check the disk drive and
then run the program again." , "Error" ,JOptionPane.INFORMATION_MESSAGE ) ;
152
153
System .exit ( 1 ) ;
154
}
155
FIGURE 8-20
Line 147 opens a new data file on disk. Because Java requires that the pro-
gram handle all possible errors, the try structure is employed in lines 145
through 148. A corresponding catch structure, lines 149 through 154, contains
the code to execute if an error occurs. The message dialog box that displays is
Box 2 from the list in Table 8-2 on page 491. If the file cannot be opened in line
147, the catch will execute and the program will close with the System.exit()
method in line 153.
Closing the Data File
Recall that the main() method required the program not to close automati-
cally when the user clicked the Close button. Therefore, you must write code to
override the windowClosing event. Figure 8-21 displays the code for the
addWindowListener() method, similar to that coded in Chapter 5.
156
addWindowListener (
157
new WindowAdapter ()
158
{
159
public void windowClosing ( WindowEvent e )
160
{
161
int answer = JOptionPane.showConfirmDialog ( null ,
"Are you sure you want to exit and submit the file?" , "File Submission" ,
JOptionPane.YES_NO_OPTION ) ;
162
if ( answer == JOptionPane.YES_OPTION )
163
System .exit ( 0 ) ;
164
}
165
}
166
) ;
FIGURE 8-21
Search WWH ::




Custom Search