Java Reference
In-Depth Information
Chapter 13
Exception Handling and Files
13.1 Handling Exceptions .................................................................... 293
13.2 Text Files ............................................................................... 299
13.2.1 The File Chooser Dialog ........................................................ 299
13.2.2 Reading from Text Files ........................................................ 300
13.2.3 Writing to Text Files ........................................................... 303
13.3 Data Files ............................................................................... 306
13.4 Summary ................................................................................ 313
13.5 Syntax .................................................................................. 313
13.6 Important Points ....................................................................... 315
13.7 Exercises ................................................................................ 316
13.8 Lab ...................................................................................... 317
13.9 Project
.................................................................................. 317
This chapter covers two important topics: files and exception handling. The topics are
covered together because every time we are working with a file, an exception can occur.
This exception can be that the file does not exist, we do not have permission to open it,
the hard disk is full and we are trying to save the file, and so on. We will cover two types
of files: text and data. For text files, we will read and write regular text to a file. When
it comes to data files, we will read and write objects to a file. We will cover checked and
unchecked exceptions. While Java forces us to handle checked exceptions, such as opening a
file, Java does not require that one handles unchecked exceptions, such as division by zero.
In the spirit of the textbook, we will describe all new Java primitives in the context of
applications. We will first extend the Notepad software and add features to read and write
to a file. Next, we will examine how the data from a bank application can be stored on the
hard disk. The latter is an interesting example because it demonstrates how to store on the
hard disk interlinked objects that belong to a multiple classes.
13.1 Handling Exceptions
Consider an application that wants to read a positive integer from the keyboard. How-
ever, the application should be bullet-proofed. In particular, the application should not
crash if the user enters a string, for example. Below is one possible way to implement such
an application.
import java . util . ;
public class Test {
public static void main(String args [])
{
int i= 1;
while (i < =0) {
i = getNumber () ;
}
293
 
Search WWH ::




Custom Search