O'Reilly logo

Big Java, 4th Edition by Cay Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Input/Output and Exception Handling

CHAPTER GOALS

  • To be able to read and write text files

  • To learn how to throw and catch exceptions

  • To be able to design your own exception classes

  • To understand the difference between checked and unchecked 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. This chapter tells you how your programs can report exceptional conditions, and how they can recover when an exceptional condition has occurred.

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, the Scanner class relies on another class, File, which describes disk files and directories. (The File class has many methods that we do not discuss in this book; for example, methods that delete or rename a file.) First construct a File object with the name of the input file, then use the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required