Java Reference
In-Depth Information
497
Chapter 11 Input/Output and Exception Handling
C HAPTER G OALS
ȗ
To be able to read and write text files
ȗ
To learn how to throw exceptions
ȗ
To be able to design your own exception classes
ȗ
To understand the difference between checked and unchecked exceptions
ȗ
To learn how to catch exceptions
ȗ
To know when and where to catch an exception
This chapter starts with a discussion of file input and output. Whenever you read or
write data, potential errors are to be expected. A file may have been corrupted or
deleted, or it may be stored on another computer that was just disconnected from the
network. In order to deal with these issues, you need to know about exception
handling. The remainder of this chapter tells you how your programs can report
exceptional conditions, and how they can recover when an exceptional condition has
occurred.
497
498
11.1 Reading and Writing Text Files
We begin this chapter by discussing the common task of reading and writing files that
contain text. Examples are files that are created with a simple text editor, such as
Windows Notepad, as well as Java source code and HTML files.
The simplest mechanism for reading text is to use the Scanner class. You already
know how to use a Scanner for reading console input. To read input from a disk
file, first construct a FileReader object with the name of the input file, then use
the FileReader to construct a Scanner object:
FileReader reader = new FileReader("input.txt");
Scanner in = new Scanner(reader);
Search WWH ::




Custom Search