Files, Streams and Object Serialization

farflungconvyancerSoftware and s/w Development

Dec 2, 2013 (3 years and 8 months ago)

1,659 views

17
Files, Streams and
Object
Serialization
OBJ ECTI VES
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
.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 17 Files, Streams and Object Serialization 3
Name:
Date:
Section:
Assignment Checklist
Exercises
Assigned:
Circle assignments
Date Due
Prelab Activities
Matching
YES NO
Fill in the Blank
14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24
Short Answer
25, 26, 27, 28, 29
Correct the Code
30, 31, 32, 33, 34
Lab Exercise
Lab Exercise 1 — Employee Hierarchy with
Object Serialization
YES NO
Follow-Up Questions and Activities
1, 2
Labs Provided by Instructor
1.
2.
3.
Postlab Activities
Coding Exercises
1, 2
Programming Challenges
1, 2
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 17 Files, Streams and Object Serialization 5
Prelab Activities
Name:
Date:
Section:
Matching
After reading Chapter 17 of Java How to Program: 8/e, answer the given questions. These questions are intended
to test and reinforce your understanding of key Java concepts. You may answer these questions either before or
during the lab.
For each term in the left column, write the letter for the description that best matches the term from the right
column.
Term
Description
1. sequential-access file
2. field
3. record
4. file
5.
InputStream

6. byte
7.
OutputStream

8.
FileWriter

9.
File
class
10. end-of-file
11.
ObjectInputSream

12.
ObjectOutputStream

13.
Serializable

a) Group of eight bits.
b) An indication that there are no more contents to read from a file.
c) File in which records are typically stored in order by the record-
key field.
d) Used by programs to obtain information about a file or directory.
e) Group of related records.
f) An
abstract
class that defines methods for performing input.
g) Group of related fields.
h) Used to read objects from a stream.
i) A tagging interface that allows objects of a class to be used with ob-
ject streams.
j) Used to write objects to a stream.
k) Composed of characters or bytes that convey meaning for one part
of a record.
l) Objects of this class write characters to a file.
m) An
abstract
class that defines methods for performing output.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Prelab Activities
Name:
Fill in the Blank
Chapter 17 Files, Streams and Object Serialization 7
Name:
Date:
Section:
Fill in the Blank
Fill in the blanks for each of the following statements:

14. Programs use classes from package
to perform Java file I/O.

15. Streams provide
between programs and files, memory or other programs across a network.

16. A collection of programs designed to create and manage databases is called a(n)
.

17. Java creates three stream objects that are associated with devices when a Java program begins executing.
These three objects are
,
and
.

18.
is an I/O-performance-enhancement technique.

19. Java views each file as a(n)
.

20. To write objects into a file, use stream objects of types
and
.

21. To read objects from a file, use stream objects of types
and
.

22.
System.out
and
System.err
are objects of class
(for text-based output).

23. Stream objects can be
to combine functionality, such as writing objects to a file.

24. The set of all characters used to write programs and represent data items on a particular computer is called
that computer’s
.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Prelab Activities
Name:
Short Answer
Chapter 17 Files, Streams and Object Serialization 9
Name:
Date:
Section:
Short Answer
In the space provided, answer each of the given questions. Your answers should be concise; aim for two or three
sentences.
25. Why is file processing useful for storing data?
26. What is the purpose of implementing interface
Serializable
in a new class?
27. Why are sequential-access files inappropriate for so-called “instant access” applications, in which a particular
record must be located immediately?
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Prelab Activities
Name:
Short Answer
10 Files, Streams and Object Serialization Chapter 17
28. What are the three predefined stream objects that you can use in a program and what is the purpose of each?
29. Describe how you would read lines of text from a text file. Specify the class(es) you would use to accomplish
this task.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Prelab Activities
Name:
Correct the Code
Chapter 17 Files, Streams and Object Serialization 11
Name:
Date:
Section:
Correct the Code
Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a compilation error, circle the error in the program and write the corrected code in the space
provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more
than one error in each program segment.]
30. The following code segment should open a file for object output:
Your answer:
31. The following code segment should open a file for object input:
Your answer:
1
ObjectOutputStream output =
2
new ObjectOutputStream( new FileOutput( "file.dat" ) );
1
FileInputStream input = new FileInputStream( "file.dat" );
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Prelab Activities
Name:
Correct the Code
12 Files, Streams and Object Serialization Chapter 17
32. The following code segment should write the object named
record
into a file. Assume that
output
is a prop-
erly defined object of class
ObjectOutputStream
.
Your answer:
33. The following code segment should open a text file for reading with a
Scanner
.
Your answer:
34. The following code segment should open a text file for writing with a
Formatter
.
Your answer:
1
output.writeObject( record );
1
Scanner input = new Scanner( "myfile.txt" );
1
Formatter output = new Formatter();
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 17 Files, Streams and Object Serialization 13
Lab Exercise
Name:
Date:
Section:
Lab Exercise 1 — Employee Hierarchy with Object Serialization
This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The
problem is divided into six parts:
1.Lab Objectives
2.Description of the Problem
3.Sample Output
4.Program Template (Fig.L 17.1 and Fig.L 17.2)
5.Problem-Solving Tips
6.Follow-Up Questions and Activities
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output; then study the template code.
Using the problem-solving tips as a guide, replace the
/*

*/
comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. The source code for the template is available
at
www.pearsonhighered.com/deitel
.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 17 of Java How to Program: 8/e. In this
lab you will practice:
• Modifying a class hierarchy to ensure that objects of the classes in the hierarchy are
Serializable
.
• Opening a file for output.
• Writing objects to a file.
The follow-up questions and activities will also give you practice:
• Opening a file for input.
• Reading objects to a file.
• Reading and writing entire arrays of
Serializable
objects.
Problem Description
Modify the
Employee
hierarchy from Figs. 10.4–10.8 to enable serialization of the classes in the hierarchy. Then,
modify the application of Fig. 10.9 to output each object in the array
employees
to a file using object serializa-
tion. [Note: In the follow-up questions, you will be asked to read these objects from the file created here.]
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Lab Exercise
Name:
Lab Exercise 1 — Employee Hierarchy with Object Serialization
14 Files, Streams and Object Serialization Chapter 17
Sample Output
Template
Employees processed individually:
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
earned: $800.00
hourly employee: Karen Price
social security number: 222-22-2222
hourly wage: $16.75; hours worked: 40.00
earned: $670.00
commission employee: Sue Jones
social security number: 333-33-3333
gross sales: $10,000.00; commission rate: 0.06
earned: $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
earned: $500.00
1
// Lab Exercise 1: Employee.java
2
// Employee abstract superclass.
3
4
5
6
public abstract class Employee
7
{
8
private String firstName;
9
private String lastName;
10
private String socialSecurityNumber;
11
12
// three-argument constructor
13
public Employee( String first, String last, String ssn )
14
{
15
firstName = first;
16
lastName = last;
17
socialSecurityNumber = ssn;
18
} // end three-argument Employee constructor
19
20
// set first name
21
public void setFirstName( String first )
22
{
23
firstName = first;
24
} // end method setFirstName
25
26
// return first name
27
public String getFirstName()
28
{
29
return firstName;
30
} // end method getFirstName
Fig. L 17.1
| Employee
abstract superclass. (Part 1 of 2.)
/* import the Serializable interface */
/* modify the following class to make all objects of its subclasses Serializable */
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Lab Exercise
Name:
Lab Exercise 1 — Employee Hierarchy with Object Serialization
Chapter 17 Files, Streams and Object Serialization 15
31
32
// set last name
33
public void setLastName( String last )
34
{
35
lastName = last;
36
} // end method setLastName
37
38
// return last name
39
public String getLastName()
40
{
41
return lastName;
42
} // end method getLastName
43
44
// set social security number
45
public void setSocialSecurityNumber( String ssn )
46
{
47
socialSecurityNumber = ssn; // should validate
48
} // end method setSocialSecurityNumber
49
50
// return social security number
51
public String getSocialSecurityNumber()
52
{
53
return socialSecurityNumber;
54
} // end method getSocialSecurityNumber
55
56
// return String representation of Employee object
57
public String toString()
58
{
59
return String.format( "%s %s\nsocial security number: %s",
60
getFirstName(), getLastName(), getSocialSecurityNumber() );
61
} // end method toString
62
63
// abstract method overridden by subclasses
64
public abstract double earnings(); // no implementation here
65
} // end abstract class Employee
1
// Lab Exercise 1: OutputEmployees.java
2
// Employee hierarchy test program.
3
4
5
public class OutputEmployees
6
{
7
public static void main( String args[] )
8
{
9
// create subclass objects
10
SalariedEmployee salariedEmployee =
11
new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
12
HourlyEmployee hourlyEmployee =
13
new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );
14
CommissionEmployee commissionEmployee =
15
new CommissionEmployee(
16
"Sue", "Jones", "333-33-3333", 10000, .06 );
Fig. L 17.2
| Employee
class hierarchy test program. (Part 1 of 2.)
Fig. L 17.1
| Employee
abstract superclass. (Part 2 of 2.)
/* import the java.io package classes necessary for writing objects into a file */
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Lab Exercise
Name:
Lab Exercise 1 — Employee Hierarchy with Object Serialization
16 Files, Streams and Object Serialization Chapter 17
Problem-Solving Tips
1.To write objects with an
ObjectOutputStream
, the objects’ class(es) must implement interface
Serial-
izable
. You can do this for all objects in the
Employee
hierarchy by simply implementing the
Serial-
izable
interface in the superclass
Employee
. Then, the
Serializable
relationship is inherited into all
of class
Employee
’s subclasses.
2.Code related to processing object streams might throw exceptions for many reasons. All
IOException
s
are checked exceptions, so these exceptions must be caught or your program will not compile.
3.If you have any questions as you proceed, ask your lab instructor for assistance.
Follow-Up Questions and Activities
1. Modify the application of Fig. 10.9 to read the objects in the file
EmployeeData.ser
into an array called
employees
, then output the contents of the array polymorphically as in Fig. 10.9.
2. Since arrays are objects in Java, entire arrays of
Serializable
objects can be output simply by passing an
array’s name to an
ObjectOutputStream
’s
writeObject
method. Similarly, an entire array of
Serializable
objects can be read with a single call to an
ObjectInputStream
’s
readObject
method. Modify class
Output-
Employees
from Lab Exercise 1 to write the entire array to the file with a single output statement. Then, mod-
ify class
InputEmployees
from Follow-Up Exercise 1 to read the entire array with a single statement.
17
BasePlusCommissionEmployee basePlusCommissionEmployee =
18
new BasePlusCommissionEmployee(
19
"Bob", "Lewis", "444-44-4444", 5000, .04, 300 );
20
21
System.out.println( "Employees processed individually:\n" );
22
23
System.out.printf( "%s\n%s: $%,.2f\n\n",
24
salariedEmployee, "earned", salariedEmployee.earnings() );
25
System.out.printf( "%s\n%s: $%,.2f\n\n",
26
hourlyEmployee, "earned", hourlyEmployee.earnings() );
27
System.out.printf( "%s\n%s: $%,.2f\n\n",
28
commissionEmployee, "earned", commissionEmployee.earnings() );
29
System.out.printf( "%s\n%s: $%,.2f\n\n",
30
basePlusCommissionEmployee,
31
"earned", basePlusCommissionEmployee.earnings() );
32
33
// create four-element Employee array
34
Employee employees[] = new Employee[ 4 ];
35
36
// initialize array with Employees
37
employees[ 0 ] = salariedEmployee;
38
employees[ 1 ] = hourlyEmployee;
39
employees[ 2 ] = commissionEmployee;
40
employees[ 3 ] = basePlusCommissionEmployee;
41
42
System.out.println( "Output the elements of the array:\n" );
43
44

45

46
} // end main
47
} // end class OutputEmployees
Fig. L 17.2
| Employee
class hierarchy test program. (Part 2 of 2.)
/* Write code here that opens the file EmployeeData.ser for object output then
writes all the elements of the array employees into the file */
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 17 Files, Streams and Object Serialization 17
Postlab Activities
Name:
Date:
Section:
Coding Exercises
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.
For each of the following problems, write a program or a program that performs the specified action(s).
1. Create a simple sequential-access file-processing program that might be used by professors to help manage
their student records. For each student, the program should obtain an ID number, the student’s first name,
the student’s last name and the student’s grade. The data obtained for each student constitutes a record for
the student and should be stored in an object of a class called
Student
. The program should save the re-
cords in a file specified by the user.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Postlab Activities
Name:
Coding Exercises
18 Files, Streams and Object Serialization Chapter 17
2. Create a simple sequential-access file-processing program to complement the program in Coding Exercise 1.
This program should open the file created by the Coding Exercise 1 program and read and display the grade
information for each student. The program should also display the class average.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Postlab Activities
Name:
Programming Challenges
Chapter 17 Files, Streams and Object Serialization 19
Name:
Date:
Section:
Programming Challenges
The Programming Challenges are more involved than the Coding Exercises and may require a significant amount
of time to complete. Write a Java program for each of the problems in this section. The answers to these problems
are available at
www.pearsonhighered.com/deitel
. Pseudocode, hints or sample outputs are provided for each
problem to aid you in your programming.

1. (Telephone-Number Word Generator) Standard telephone keypads contain the digits zero through nine. The
numbers two through nine each have three letters associated with them. (See Fig.L 17.3.) Many people find
it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop
seven-letter words that correspond to their phone numbers. For example, a person whose telephone number
is 686-2377 might use the correspondence indicated in Fig.L 17.3 to develop the seven-letter word “NUM-
BERS.” Each seven-letter word corresponds to exactly one seven-digit telephone number. The restaurant
wishing to increase its takeout business could surely do so with the number 825-3688 (i.e., “TAKEOUT”).
Each seven-letter phone number corresponds to many separate seven-letter words. Unfortunately, most
of these words represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a
barbershop would be pleased to know that the shop’s telephone number, 424-7288, corresponds to “HAIR-
CUT.” The owner of a liquor store would, no doubt, be delighted to find that the store’s number, 233-7226,
corresponds to “BEERCAN.” A veterinarian with the phone number 738-2273 would be pleased to know
that the number corresponds to the letters “PETCARE.” An automotive dealership would be pleased to
know that the dealership number, 639-2277, corresponds to “NEWCARS.”
Write a program that, given a seven-digit number, uses a
Formatter
object to write to a file every possi-
ble seven-letter word combination corresponding to that number. There are 2187 (3
7
) such combinations.
Avoid phone numbers with the digits 0 and 1.
Digit
Letters
2
A B C
3
D E F
4
G H I
5
J K L
6
M N O
7
P R S
8
T U V
9
W X Y
Fig. L 17.3 |
Telephone keypad digits and letters.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Postlab Activities
Name:
Programming Challenges
20 Files, Streams and Object Serialization Chapter 17
2. (Student Poll) Figure 7.8 in Java How to Program contains an array of survey responses that is hard coded into
the program. Suppose we wish to process survey results that are stored in a file. This exercise requires two
separate programs. First, create an application that prompts the user for survey responses and outputs each
response to a file. Use a
Formatter
to create a file called
numbers.txt
. Each integer should be written using
method format. Then modify the program in Figure 7.8 to read the survey responses from
numbers.txt
.
The responses should be read from the file by using a
Scanner
. Method
nextInt
should be used to input
one integer at a time from the file. The program should continue to read responses until it reaches the end
of file. The results should be output to the text file
"output.txt"
.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.