Starting Out with Java: From Control Structures through Objects

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Starting Out With Java 5 (Early Objects) Chapter 10 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
12-2 Chapter Topics Chapter 12 discusses the following main topics: Part I: Exceptions Handling Exceptions Throwing Exceptions Part II: More about Input/Output.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 4: Loops and Files
Chapter 9 Streams and File I/O Overview of Streams and File I/O
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exceptions and Advanced File I/O
Starting Out with Java: From Control Structures through Objects
1 Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
Binary Files, Random Access Files Binary Files The way data is stored in memory is sometimes called the raw binary format. Data can be stored in.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 10 Exceptions and Advanced File I/O.
Chapter 11 Exceptions and Input/Output Operations.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 9.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Java IO Exploring the java.io package and living to talk about it.
Chapter 12 Exceptions and Advanced File I/O. 2 Contents I. Handling Exceptions II. Throwing Exceptions III. Advanced Topics 1. Binary Files 2. Random.
Chapter 12: Exceptions and Advanced File I/O
Exceptions Chapter 9.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
Introduction Exception handling Exception Handles errors
Lecture 4- Loops and Files
Introduction to Exceptions in Java
Exceptions and Advanced File I/O
Accessing Files in Java
Testing and Exceptions
File Input and Output TOPICS File Input Exception Handling File Output.
Chapter 4: Loops and Files
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
Chapter 11: Exceptions and Advanced File I/O
Computer Programming with JAVA
Chapter 12: Exceptions and Advanced File I/O
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Dr. Sampath Jayarathna Cal Poly Pomona
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions.
Starting Out with Java: From Control Structures through Objects
Ch.4 – 5 Topics The auto Increment and Decrement Operators
Exceptions.
Presentation transcript:

Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis Source Code: Chapter 11

Code Listing 11-1 (BadArray.java) 1 /** 2 This program causes an error and crashes. 3 */ 4 5 public class BadArray 6 { 7 public static void main(String[] args) 8 { 9 10 int[] numbers = { 1, 2, 3 }; 11 12 14 for (int i = 0; i <= 3; i++) 15 System.out.println(numbers[i]); 16 } 17 } Program Output 1 2 3 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at BadArray.main(BadArray.java:15)

Code Listing 11-2 (OpenFile.java) import java.io.*; // For File class and //FileNotFoundException 2 import java.util.Scanner; // For the Scanner class 3 import javax.swing.JOptionPane; // For the JOptionPane class 4 5 /** 6 This program demonstrates how a FileNotFoundException 7 exception can be handled. 8 */ 9 10 public class OpenFile 11 { 12 public static void main(String[] args) 13 { 14 File file; 15 Scanner inputFile; 16 String fileName; 17 18 // Get a file name from the user. 19 fileName = JOptionPane.showInputDialog("Enter " + 20 "the name of a file:"); 21 22 (Continued)

(23 try 24 { 25 file = new File(fileName); 24 { 25 file = new File(fileName); 26 inputFile = new Scanner(file); // Scanner object throws exception 27 JOptionPane.showMessageDialog(null, 28 "The file was found."); 29 } 30 catch (FileNotFoundException e) 31 { 32 JOptionPane.showMessageDialog(null, 33 "File not found."); 34 } 35 36 JOptionPane.showMessageDialog(null, "Done."); 37 System.exit(0); 38 } 39 }

Code Listing 11-3 (ExceptionMessage.java) 1 import java.io.*; // For file I/O classes 2 import java.util.Scanner; // For the Scanner class 3 import javax.swing.JOptionPane; // For the JOptionPane class 4 5 /** 6 This program demonstrates how a FileNotFoundException 7 exception can be handled. 8 */ 9 10 public class ExceptionMessage 11 { 12 public static void main(String[] args) 13 { 14 File file; 15 Scanner inputFile; 16 String fileName; 17 18 19 fileName = JOptionPane.showInputDialog("Enter " + 20 "the name of a file:"); 21 22 // Attempt to open the file. (Continued)

23 try 24 { 25 file = new File(fileName); 26 inputFile = new Scanner(file); 27 JOptionPane.showMessageDialog(null, 28 "The file was found."); 29 } 30 catch (FileNotFoundException e) 31 { 32 JOptionPane.showMessageDialog(null, e.getMessage()); 33 } 34 JOptionPane.showMessageDialog(null, "Done."); 36 System.exit(0); 37 } } Each exception object has a method names “ getMessage()” that can be used to retrieve the default error message for that exception.

Conversion error: For input string: "abcde" Code Listing 11-4 (ParseIntError.java) 1 /** 2 This program demonstrates how the Integer.parseInt 3 method throws an exception. 4 */ 5 6 public class ParseIntError 7 { 8 public static void main(String[] args) 9 { 10 String str = "abcde"; 11 int number; 12 13 try 14 { 15 number = Integer.parseInt(str); 16 } 17 catch (NumberFormatException e) 18 { 19 System.out.println("Conversion error: " + 20 e.getMessage()); 21 } 22 } 23 } Program Output Conversion error: For input string: "abcde"

Code Listing 11-5 (SalesReport.java) import java.io.*; // For File class and // FileNotFoundException 2 import java.util.*; // For Scanner and // InputMismatchException 3 import java.text.DecimalFormat; // For the DecimalFormat class 4 import javax.swing.JOptionPane; // For the JOptionPane class 5 6 /** 7 This program demonstrates how multiple exceptions can 8 be caught with one try statement. 9 */ 10 11 public class SalesReport 12 { 13 public static void main(String[] args) 14 { 15 String filename = "SalesData.txt"; // File name 16 int months = 0; 17 double oneMonth; // One month's sales 18 double totalSales = 0.0; // Total sales 19 double averageSales; // Average sales 20 22 DecimalFormat dollar = new DecimalFormat(“#,##0.00”);

28 File file = new File(filename); 25 try 26 { 27 28 File file = new File(filename); 29 Scanner inputFile = new Scanner(file); 30 32 while (inputFile.hasNext()) 33 { 34 35 oneMonth = inputFile.nextDouble(); 36 38 totalSales += oneMonth; 41 months++; 42 } 43 44 inputFile.close(); (Continued)

48 averageSales = totalSales / months; 49 50 51 JOptionPane.showMessageDialog(null, 52 "Number of months: " + months + 53 "\nTotal Sales: $" + 54 dollar.format(totalSales) + 55 "\nAverage Sales: $" + 56 dollar.format(averageSales)); 57 } 58 catch(FileNotFoundException e) 59 { 60 // Thrown by the Scanner constructor 62 JOptionPane.showMessageDialog(null, 63 "The file " + filename + 64 " does not exist."); 65 } 66

catch (InputMismatchException e) 67 { 68 // Thrown by the Scanner class's nextDouble 69 // method when a non-numeric value is found. 70 JOptionPane.showMessageDialog(null, 71 "Non-numeric data found " + 72 "in the file."); 73 } 74 75 System.exit(0); 76 } 77 }

Code Listing 11-6 (SalesReport2.java) 1 import java.io.*; 2 import java.util.*; 3 import java.text.DecimalFormat; 4 import javax.swing.JOptionPane; 5 6 /** 7 This program demonstrates how exception handlers can 8 be used to recover from errors. 9 */ 10 11 public class SalesReport2 12 { 13 public static void main(String[] args) 14 { 15 String filename = "SalesData.txt"; 16 int months = 0; 17 double oneMonth; 18 double totalSales = 0.0; 19 double averageSales; 20 22 DecimalFormat dollar = 23 new DecimalFormat("#,##0.00");

27 Scanner inputFile = openFile(filename); 28 29 // If the openFile method returned null, then // the file was not found. Get a new file name. 31 while (inputFile == null) 32 { 33 filename = JOptionPane.showInputDialog( 34 "ERROR: " + filename + 35 " does not exist.\n" + 36 "Enter another file name: "); 37 inputFile = openFile(filename); 38 } 39 40 41 while (inputFile.hasNext()) 42 { 43 try 44 { 45 // Get a month's sales amount. (Continued)

46 oneMonth = inputFile.nextDouble(); 47 49 totalSales += oneMonth; 50 51 52 months++; 53 } 54 catch(InputMismatchException e) 55 { 56 57 JOptionPane.showMessageDialog(null, 58 "Non-numeric data found in the file.\n" + 59 "The invalid record will be skipped."); 60 61 // Skip past the invalid data. 62 inputFile.nextLine(); 63 } // END OF CATCH BLOCK 64 }// END OF WHILE LOOP 65 66 // Close the file. 67 inputFile.close(); (Continued)

70 averageSales = totalSales / months; 71 72 // Display the results. 73 JOptionPane.showMessageDialog(null, 74 "Number of months: " + months + 75 "\nTotal Sales: $" + 76 dollar.format(totalSales) + 77 "\nAverage Sales: $" + 78 dollar.format(averageSales)); 79 System.exit(0); // END OF MAIN() 80 } 81 82 /** 83 The openFile method opens the specified file and 84 returns a reference to a Scanner object. 85 @param filename The name of the file to open. 86 @return A Scanner reference, if the file exists 87 Otherwise, null is returned. 88 */ 89 (Continued)

90 public static Scanner openFile(String filename) 91 { 92 Scanner scan; 93 95 try 96 { 97 File file = new File(filename); 98 scan = new Scanner(file); 99 } 100 catch(FileNotFoundException e) 101 { 102 scan = null; 103 } 104 105 return scan; 106 } 107 }

Code Listing 11-7 (StackTrace.java) 1 /** 2 This program demonstrates the stack trace that is 3 produced when an exception is thrown. 4 */ 5 6 public class StackTrace 7 { 8 public static void main(String[] args) 9 { 10 System.out.println("Calling myMethod..."); 11 myMethod(); 12 System.out.println("Method main is done."); 13 } 14 15 /** 16 MyMethod 17 */ 18 19 public static void myMethod() 20 { 21 System.out.println("Calling produceError..."); 22 produceError(); (Continued)

23 System.out.println("myMethod is done."); 24 } 25 26 /** 27 produceError 28 */ 29 30 public static void produceError() 31 { 32 String str = "abc"; 33 34 // The following statement will cause an error. 35 System.out.println(str.charAt(3)); 36 System.out.println("produceError is done."); 37 } } Program Output Calling myMethod... Calling produceError... Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.lang.String.charAt(Unknown Source) at StackTrace.produceError(StackTrace.java:35) at StackTrace.myMethod(StackTrace.java:22) at StackTrace.main(StackTrace.java:11)

Code Listing 11-8 (MultiCatch.java) 1 import java.io.*; // For File class and FileNotFoundException 2 import java.util.*; // For Scanner and InputMismatchException 3 4 /** 5 This program demonstrates how multiple exceptions can 6 be caught with a single catch clause. 7 */ 8 9 public class MultiCatch 10 { 11 public static void main(String[] args) 12 { 13 int number; // To hold a number from the file 14 15 try 16 { 17 // Open the file. 18 File file = new File("Numbers.txt"); 19 Scanner inputFile = new Scanner(file); 20 21 // Process the contents of the file. 22 while (inputFile.hasNext()) (Continued)

(Continued) Code Listing 11-8 (MultiCatch.java) 23 { 24 // Get a number from the file. 25 number = inputFile.nextInt(); 26 27 // Display the number. 28 System.out.println(number); 29 } 30 31 // Close the file. 32 I nputFile.close(); 33 } 34 catch(FileNotFoundException | InputMismatchException ex) 35 { 36 // Display an error message. 37 System.out.println("Error processing the file."); 38 } 39 } 40 }

Code Listing 11-9 (DateComponentExceptionDemo.java) 1 /** 2 This program demonstrates how the DateComponent 3 class constructor throws an exception. 4 */ 5 6 public class DateComponentExceptionDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a null String reference. 11 String str = null; 12 13 // Attempt to pass the null reference to 14 // the DateComponent constructor. 15 try 16 { 17 DateComponent dc = new DateComponent(str); 18 } 19 catch (IllegalArgumentException e) 20 { 21 System.out.println(e.getMessage()); 22 } 23 } 24 } Program Output null reference passed to DateComponent constructor

Code Listing 11-10 (NegativeStartingBalance.java) 1 /** 2 NegativeStartingBalance exceptions are thrown by the 3 BankAccount class when a negative starting balance is 4 passed to the constructor. 5 */ 6 7 public class NegativeStartingBalance 8 extends Exception 9 { 10 /** 11 This constructor uses a generic 12 error message. 13 */ 14 15 public NegativeStartingBalance() 16 { 17 super("Error: Negative starting balance"); 18 } 19 20 /** 21 This constructor specifies the bad starting 22 balance in the error message. (Continued)

(Continued) Code Listing 11-10 (NegativeStartingBalance.java) 23 @param The bad starting balance. 24 */ 25 26 public NegativeStartingBalance(double amount) 27 { 28 super("Error: Negative starting balance: " + 29 amount); 30 } 31 }

Code Listing 11-11 (AccountTest.java) 1 /** 2 This program demonstrates how the BankAccount 3 class constructor throws custom exceptions. 4 */ 5 6 public class AccountTest 7 { 8 public static void main(String [] args) 9 { 10 // Force a NegativeStartingBalance exception. 11 try 12 { 13 BankAccount account = 14 new BankAccount(-100.0); 15 } 16 catch(NegativeStartingBalance e) 17 { 18 System.out.println(e.getMessage()); 19 } 20 } 21 } Program Output Error: Negative starting balance: -100.0

Code Listing 11-12 (WriteBinaryFile.java) 1 import java.io.*; 2 3 /** 4 This program opens a binary file and writes the contents 5 of an int array to the file. 6 */ 7 8 public class WriteBinaryFile 9 { 10 public static void main(String[] args) 11 throws IOException 12 { 13 // An array to write to the file 14 int[] numbers = { 2, 4, 6, 8, 10, 12, 14 }; 15 16 // Create the binary output objects. 17 FileOutputStream fstream = 18 new FileOutputStream("Numbers.dat"); 19 DataOutputStream outputFile = 20 new DataOutputStream(fstream); 21 22 System.out.println("Writing the numbers to the file..."); (Continued)

(Continued) Code Listing 11-12 (WriteBinaryFile.java) 23 24 // Write the array elements to the file. 25 for (int i = 0; i < numbers.length; i++) 26 outputFile.writeInt(numbers[i]); 27 28 System.out.println("Done."); 29 30 // Close the file. 31 outputFile.close(); 32 } 33 } Program Output Writing the numbers to the file... Done.

Code Listing 11-13 (ReadBinaryFile.java) 1 import java.io.*; 2 3 /** 4 This program opens a binary file, reads 5 and displays the contents. 6 */ 7 8 public class ReadBinaryFile 9 { 10 public static void main(String[] args) 11 throws IOException 12 { 13 int number; // A number read from the file 14 boolean endOfFile = false; // EOF flag 15 16 // Create the binary file input objects. 17 FileInputStream fstream = 18 new FileInputStream("Numbers.dat"); 19 DataInputStream inputFile = 20 new DataInputStream(fstream); 21 22 System.out.println("Reading numbers from the file:"); (Continued)

(Continued) Code Listing 11-13 (ReadBinaryFile.java) 23 24 // Read the contents of the file. 25 while (!endOfFile) 26 { 27 try 28 { 29 number = inputFile.readInt(); 30 System.out.print(number + " "); 31 } 32 catch (EOFException e) 33 { 34 endOfFile = true; 35 } 36 } 37 38 System.out.println("\nDone."); 39 40 // Close the file. 41 inputFile.close(); 42 } 43 } Program Output Reading numbers from the file: 2 4 6 8 10 12 14 Done.

Code Listing 11-14 (WriteLetters.java) 1 import java.io.*; 2 3 /** 4 This program uses a RandomAccessFile object to 5 create the file Letters.dat. The letters of the 6 alphabet are written to the file. 7 */ 8 9 public class WriteLetters 10 { 11 public static void main(String[] args) 12 throws IOException 13 { 14 // The letters array has all 26 letters. 15 char[] letters = { 16 'a', 'b', 'c', 'd', 'e', 'f', 'g', 17 'h', 'i', 'j', 'k', 'l', 'm', 'n', 18 'o', 'p', 'q', 'r', 's', 't', 'u', 19 'v', 'w', 'x', 'y', 'z' }; 20 21 System.out.println("Opening the file."); 22 23 // Open a file for reading and writing. (Continued)

(Continued) Code Listing 11-14 (WriteLetters.java) 24 RandomAccessFile randomFile = 25 new RandomAccessFile("Letters.dat", "rw"); 26 27 System.out.println("Writing data to the file..."); 28 29 // Sequentially write the letters array to the file. 30 for (int i = 0; i < letters.length; i++) 31 randomFile.writeChar(letters[i]); 32 33 // Close the file. 34 randomFile.close(); 35 36 System.out.println("Done."); 37 } 38 } Program Output Opening the file. Writing data to the file... Done.

Code Listing 11-15 (ReadRandomLetters.java) 1 import java.io.*; 2 3 /** 4 This program uses the RandomAccessFile class to open 5 the file Letters.dat and randomly read letters from 6 different locations. 7 */ 8 9 public class ReadRandomLetters 10 { 11 public static void main(String[] args) throws IOException 12 { 13 final int CHAR_SIZE = 2; // 2 byte characters 14 long byteNum; // The byte number 15 char ch; // A character from the file 16 17 // Open the file for reading. 18 RandomAccessFile randomFile = 19 new RandomAccessFile("Letters.dat", "r"); 20 21 // Move to the character 5. This is the 6th 22 // character from the beginning of the file. (Continued)

(Continued) Code Listing 11-15 (ReadRandomLetters.java) 23 byteNum = CHAR_SIZE * 5; 24 randomFile.seek(byteNum); 25 26 // Read the character stored at this location 27 // and display it. Should be the letter f. 28 ch = randomFile.readChar(); 29 System.out.println(ch); 30 31 // Move to character 10 (the 11th character), 32 // read the character, and display it. 33 // Should be the letter k. 34 byteNum = CHAR_SIZE * 10; 35 randomFile.seek(byteNum); 36 ch = randomFile.readChar(); 37 System.out.println(ch); 38 39 // Move to character 3 (the 4th character), 40 // read the character, and display it. 41 // Should be the letter d. 42 byteNum = CHAR_SIZE * 3; 43 randomFile.seek(byteNum); 44 ch = randomFile.readChar(); (Continued)

(Continued) Code Listing 11-15 (ReadRandomLetters.java) 45 System.out.println(ch); 46 47 // Close the file. 48 randomFile.close(); 49 } 50 } Program Output f k d

Code Listing 11-16 (SerializeObjects.java) 1 import java.io.*; 2 import java.util.Scanner; 3 4 /** 5 This program serializes the objects in an array of 6 BankAccount2 objects. 7 */ 8 9 public class SerializeObjects 10 { 11 public static void main(String[] args) 12 throws IOException 13 { 14 double balance; // An account balance 15 final int NUM_ITEMS = 3; // Number of accounts 16 17 // Create a Scanner object for keyboard input. 18 Scanner keyboard = new Scanner(System.in); 19 20 // Create a BankAccount2 array 21 BankAccount2[] accounts = 22 new BankAccount2[NUM_ITEMS]; (Continued)

(Continued) Code Listing 11-16 (SerializeObjects.java) 23 24 // Populate the array. 25 for (int i = 0; i < accounts.length; i++) 26 { 27 // Get an account balance. 28 System.out.print("Enter the balance for " + 29 "account " + (i + 1) + ": "); 30 balance = keyboard.nextDouble(); 31 32 // Create an object in the array. 33 accounts[i] = new BankAccount2(balance); 34 } 35 36 // Create the stream objects. 37 FileOutputStream outStream = 38 new FileOutputStream("Objects.dat"); 39 ObjectOutputStream objectOutputFile = 40 new ObjectOutputStream(outStream); 41 42 // Write the serialized objects to the file. 43 for (int i = 0; i < accounts.length; i++) 44 { (Continued)

(Continued) Code Listing 11-16 (SerializeObjects.java) 45 objectOutputFile.writeObject(accounts[i]); 46 } 47 48 // Close the file. 49 objectOutputFile.close(); 50 51 System.out.println("The serialized objects " + 52 "were written to the Objects.dat file."); 53 } 54 } Program Output with Example Input Shown in Bold Enter the balance for account 1: 5000.0 [Enter] Enter the balance for account 2: 2500.0 [Enter] Enter the balance for account 3: 1800.0 [Enter] The serialized objects were written to the Objects.dat file.

Code Listing 11-17 (DeserializeObjects.java) 1 import java.io.*; 2 3 /** 4 This program deserializes the objects in the Objects.dat 5 file and stores them in an array. 6 */ 7 8 public class DeserializeObjects 9 { 10 public static void main(String[] args) 11 throws Exception 12 { 13 double balance; // An account balance 14 final int NUM_ITEMS = 3; // Number of accounts 15 16 // Create the stream objects. 17 FileInputStream inStream = 18 new FileInputStream("Objects.dat"); 19 ObjectInputStream objectInputFile = 20 new ObjectInputStream(inStream); 21 22 // Create a BankAccount2 array 23 BankAccount2[] accounts = (Continued)

(Continued) Code Listing 11-17 (DeserializeObjects.java) 24 new BankAccount2[NUM_ITEMS]; 25 26 // Read the serialized objects from the file. 27 for (int i = 0; i < accounts.length; i++) 28 { 29 accounts[i] = 30 (BankAccount2) objectInputFile.readObject(); 31 } 32 33 // Close the file. 34 objectInputFile.close(); 35 36 // Display the objects. 37 for (int i = 0; i < accounts.length; i++) 38 { 39 System.out.println("Account " + (i + 1) + 40 " $ " + accounts[i].getBalance()); 41 } 42 } 43 } Program Output Account 1 $ 5000.0 Account 2 $ 2500.0 Account 3 $ 1800.0