Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
630
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

getMessage method of class Throwable getMethodName method of class StackTraceElement getStackTrace method of class Throwable InputMismatchException class

postcondition

precondition

printStackTrace method of class THRowable release a resource

resource leak

resumption model of exception handling rethrowing an exception

RuntimeException class

stack trace

StackTraceElement class stack unwinding standard error stream standard output stream synchronous error

System.err stream

termination model of exception handling throw an exception

tHRow keyword throw point throw statement

Throwable class

tHRows clause

try block

TRy statement

TRy...catch...finally exception-handling mechanism

uncaught exception

unchecked exceptions

[Page 669 (continued)]

Self-Review Exercises

13.1 List five common examples of exceptions.

13.2 Give several reasons why exception-handling techniques should not be used for conventional program control.

13.3 Why are exceptions particularly appropriate for dealing with errors produced by methods of classes in the Java API?

13.4 What is a "resource leak"?

13.5 If no exceptions are thrown in a TRy block, where does control proceed to when the try block completes execution?

13.6 Give a key advantage of using catch( Exception exceptionName ).

13.7 Should a conventional application catch Error objects? Explain.

13.8 What happens if no catch handler matches the type of a thrown object?

13.9 What happens if several catch blocks match the type of the thrown object?

13.10 Why would a programmer specify a superclass type as the type in a catch block?

13.11 What is the key reason for using finally blocks?

13.12 What happens when a catch block throws an Exception?

13.13 What does the statement tHRow exceptionReference do?

13.14 What happens to a local reference in a try block when that block throws an

Exception?

[Page 670]

Answers to Self-Review Exercises

13.1 Memory exhaustion, array index out of bounds, arithmetic overflow, division by zero, invalid method parameters.

13.2 (a) Exception handling is designed to handle infrequently occurring situations that often result in program termination, not situations that arise all the time. (b) Flow of control with conventional control structures is generally clearer and more efficient than with exceptions. (c) The "additional" exceptions can get in the way of genuine errortype exceptions. It becomes more difficult for the programmer to keep track of the larger number of exception cases.

13.3 It is unlikely that methods of classes in the Java API could perform error processing that would meet the unique needs of all users.

13.4 A "resource leak" occurs when an executing program does not properly release a resource when it is no longer needed.

13.5 The catch blocks for that try statement are skipped, and the program resumes execution after the last catch block. If there is a finally block, it is executed first; then the program resumes execution after the finally block.

13.6 The form catch( Exception exceptionName ) catches any type of exception thrown in a try block. An advantage is that no thrown Exception can slip by without being caught. The programmer can then decide to handle the exception or possibly rethrow it.

13.7 Errors are usually serious problems with the underlying Java system; most programs will not want to catch Errors because the program will not be able to recover from such problems.

13.8 This causes the search for a match to continue in the next enclosing try statement. If there is a finally block, it will be executed before the exception goes to the next enclosing TRy statement. If there are no enclosing try statements for which there are matching catch blocks, and the exception is checked, a compilation error occurs. If there are no enclosing try statements for which there are matching catch blocks and the exception is unchecked, a stack trace is printed and the current thread terminates early.

13.9 The first matching catch block after the try block is executed.

13.10 This enables a program to catch related types of exceptions and process them in a uniform manner. However, it is often useful to process the subclass types individually for more precise exception handling.

13.11 The finally block is the preferred means for releasing resources to prevent resource leaks.

13.12 First, control passes to the finally block if there is one. Then the exception will be processed by a catch block (if one exists) associated with an enclosing try block (if one exists).

13.13 It rethrows the exception for processing by an exception handler of an enclosing try statement, after the finally block of the current try statement executes.

13.14 The reference goes out of scope, and the reference count for the object is decremented. If the reference count becomes zero, the object is marked for garbage collection.

[Page 670 (continued)]

Exercises

13.15List the various exceptional conditions that have occurred in programs throughout this text so far. List as many additional exceptional conditions as you can. For each of these, describe briefly how a program typically would handle the exception by using the exception-handling techniques discussed in this chapter. Some typical exceptions are division by zero, arithmetic overflow, array index out of bounds, etc.

[Page 671]

13.16Until this chapter, we have found that dealing with errors detected by constructors is a bit awkward. Explain why exception handling is an effective means for dealing with constructor failure.

13.17(Catching Exceptions with Superclasses) Use inheritance to create an exception superclass (called ExceptionA) and exception subclasses ExceptionB and ExceptionC, where ExceptionB inherits from ExceptionA and ExceptionC inherits from ExceptionB. Write a program to demonstrate that the catch block for type

ExceptionA catches exceptions of types ExceptionB and ExceptionC.

13.18(Catching Exceptions Using Class Exception) Write a program that demonstrates how various exceptions are caught with

catch ( Exception exception )

This time, define classes ExceptionA (which inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your program, create try blocks that throw exceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be caught with catch blocks specifying type Exception.

13.19(Order of catch Blocks) Write a program that shows that the order of catch blocks is important. If you try to catch a superclass exception type before a subclass type, the compiler should generate errors.

13.20(Constructor Failure) Write a program that shows a constructor passing information about constructor failure to an exception handler. Define class SomeException, which throws an Exception in the constructor. You program should try to create an object of type SomeException, and catch the exception that is thrown from the constructor.

13.21(Rethrowing Exceptions) Write a program that illustrates rethrowing an exception. Define methods someMethod and someMethod2. Method someMethod2 should initially throw an exception. Method someMethod should call someMethod2, catch the exception and rethrow it. Call someMethod from method main, and catch the rethrown exception. Print the stack trace of this exception.

13.22(Catching Exceptions Using Outer Scopes) Write a program showing that a method with its own TRy block does not have to catch every possible error generated within the try. Some exceptions can slip through to, and be handled in, other scopes.

[Page 672]

Chapter 14. Files and Streams

I can only assume that a "Do Not File" document is filed in a "Do Not File" file.

Senator Frank Church Senate Intelligence Subcommittee Hearing, 1975

Consciousness ... does not appear to itself chopped up in bits. ... A "river" or a "stream" are the metaphors by which it is most naturally described.

William James

I read part of it all the way through.

Samuel Goldwyn

A great memory does not make a philosopher, any more than a dictionary can be called grammar.

John Henry, Cardinal Newman

OBJECTIVES

In this chapter you will learn:

To create, read, write and update files.

To use class File to retrieve information about files and directories.

The Java input/output stream class hierarchy.

The differences between text files and binary files.

Sequential-access and random-access file processing.

To use classes Scanner and Formatter to process text files.

To use the FileInputStream and FileOutputStream classes.

To use a JFileChooser dialog.

To use the ObjectInputStream and ObjectOutputStream classes.

To use class RandomAccessFile.

[Page 673]

Outline

14.1 Introduction

14.2 Data Hierarchy

14.3 Files and Streams

14.4 Class File

14.5 Sequential-Access Text Files

14.5.1 Creating a Sequential-Access Text File

14.5.2 Reading Data from a Sequential-Access Text File

14.5.3 Case Study: A Credit-Inquiry Program

14.5.4 Updating Sequential-Access Files

14.6 Object Serialization

14.6.1 Creating a Sequential-Access File Using Object Serialization

14.6.2 Reading and Deserializing Data from a Sequential-Access File

14.7 Random-Access Files

14.7.1 Creating a Random-Access File

14.7.2 Writing Data Randomly to a Random-Access File

14.7.3 Reading Data Sequentially from a Random-Access File

14.7.4 Case Study: A Transaction-Processing Program

14.8 Additional java.io Classes

14.9 Opening Files with JFileChooser

14.10 Wrap-Up

Summary

Terminology

Self-Review Exercises

Answers to Self-Review Exercises

Exercises

[Page 673 (continued)]

14.1. Introduction

Storage of data in variables and arrays is temporarythe data is lost when a local variable goes out of scope or when the program terminates. Computers use files for long-term retention of large amounts of data, even after the programs that created the data terminate. You use files every day for tasks such as writing an essay or creating a spreadsheet. We refer to data maintained in files as persistent data because it exists beyond the duration of program execution. Computers store files on secondary storage devices such as hard disks, optical disks and magnetic tapes. In this chapter, we explain how Java programs create, update and process data files.

File processing is one of the most important capabilities a language must have to support commercial applications, which typically store and process massive amounts of persistent data. In this chapter, we discuss Java's powerful file-processing and stream input/ output features. The term "stream" refers to ordered data that is read from or written to a file. We discuss streams in more detail in Section 14.3.

File processing is a subset of Java's stream-processing capabilities, which enable a program to read and write data in memory, in files and over network connections. We have two goals in this chapterto introduce file-processing concepts (making the reader more comfortable with using files programmatically) and to provide the reader with sufficient stream-processing capabilities to support the networking features introduced in Chapter 24, Networking. Java provides substantial stream-processing capabilitiesfar more than we can cover in one chapter. We discuss three forms of file processing heretext-file processing, object serialization and random-access file processing.

[Page 674]

We begin by discussing the hierarchy of data contained in files. We then cover Java's architecture for handling files programmatically by discussing several classes in package java.io. Next we explain that data can be stored in two different types of filestext files and binary filesand cover the differences between them. We demonstrate retrieving information about a file or directory using class File and then devote several sections to the different mechanisms for writing data to and reading data from files. First we demonstrate creating and manipulating sequential-access text files. Working with text files allows the reader to quickly and easily start manipulating files. As you will learn, however, it is difficult to read data from text files back into object form. Fortunately, many object-oriented languages (including Java) provide ways to write objects to and read objects from files (known as object serialization and deserialization). To demonstrate this, we recreate some of the sequential-access programs that used text files, this time by storing objects in binary files. We then consider random-access files, which enable us to directly and quickly access specific portions of a file. Understanding random-access files provides a foundation for understanding databases, discussed in Chapter 25, Accessing Databases with JDBC.

[Page 674 (continued)]

14.2. Data Hierarchy

Ultimately, a computer processes all data items as combinations of zeros and ones, because it is simple and economical for engineers to build electronic devices that can assume two stable statesone representing 0 and the other representing 1. It is remarkable that the impressive functions performed by computers involve only the most fundamental manipulations of 0s and 1s.

The smallest data item in a computer can assume the value 0 or the value 1. Such a data item is called a bit (short for "binary digit"a digit that can assume one of two values). Computer circuitry performs various simple bit manipulations, such as examining the value of a bit, setting the value of a bit and reversing the value of a bit (from 1 to 0 or from 0 to 1).

It is cumbersome for programmers to work with data in the low-level form of bits. Instead, programmers prefer to work with data in such forms as decimal digits (09), letters (AZ and az), and special symbols (e.g., $, @, %, &, *, (, ), , +, ", :, ? and / ). Digits, letters and special symbols are known as characters. The computer's character set is the set of all the characters used to write programs and represent data items. Computers process only 1s and 0s, so a computer's character set represents every character as a pattern of 1s and 0s. Characters in Java are Unicode characters composed of two bytes, each composed of eight bits. Java contains a data type, byte, that can be used to represent byte data. The Unicode character set contains characters for many of the world's languages. See Appendix F for more information on this character set. See Appendix B, ASCII Character Set for more information on the ASCII (American Standard Code for Information Interchange) character set, a subset of the Unicode character set that represents uppercase and lowercase letters, digits and various common special characters.

Just as characters are composed of bits, fields are composed of characters or bytes. A field is a group of characters or bytes that conveys meaning. For example, a field consisting of uppercase and lowercase letters can be used to represent a person's name.

[Page 675]

Data items processed by computers form a data hierarchy that becomes larger and more complex in structure as we progress from bits to characters to fields, and so on.

Typically, several fields compose a record (implemented as a class in Java). In a payroll system, for example, the record for an employee might consist of the following fields (possible types for these fields are shown in parentheses):

Employee identification number (int)

Name (String)

Address (String)

Hourly pay rate (double)

Number of exemptions claimed (int)

Year-to-date earnings (int or double)

Amount of taxes withheld (int or double)

Thus, a record is a group of related fields. In the preceding example, all the fields belong to the same employee. Of course, a company might have many employees and thus have a payroll record for each employee. A file is a group of related records. [Note: More generally, a file contains arbitrary data in arbitrary formats. In some operating systems, a file is viewed as nothing more than a collection of bytesany organization of the bytes in a file (e.g., organizing the data into records) is a view created by the applications programmer.] A company's payroll file normally contains one record for each employee. Thus, a payroll file for a small company might contain only 22 records, whereas one for a large company might contain 100,000 records. It is not unusual for a company to have many files, some containing billions, or even trillions, of characters of information. Figure 14.1 illustrates a portion of the data hierarchy.

Figure 14.1. Data hierarchy.