Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
Java How to Program, 6/e

ISBN:
0-13-148398-6
© 2005
pages: 1576
Buy the Book!
Amazon logo
InformIT logo

The following Java tutorial introduces object serialization--Java's built-in mechanism for manipulating objects as streams of bytes. Object serialization provides the foundation for Java's remote method invocation (RMI) capabilties that enable Java programs that are distributed over a network to invoke each others so-called "remote methods." RMI is used frequently in distributed enterprise applications that are built with Java Enterprise Edition (Java EE). In this tutorial, we demonstrate object serialization by writing entire objects to and reading entire objects from files on disk. This tutorial is intended for students and professionals who are already familiar with Java programming. Download the examples for this tutorial here.

[Notes: This tutorial is an excerpt (Section 14.6) of Chapter 14, Files and Streams, from our best-selling textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. When you purchase this book you also get free access to the Web-based Java Multimedia Cyber Classroom, 6/e, for six months. The Cyber Classroom includes audio descriptions of the examples in Chapters 1-14, solutions to approximately one-half of the end-of-chapter exercises, interactive true/false self-assessment questions and a searchable Web-based e-book. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp. 697-706. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

Introduction to Object Serialization (Continued)

14.6.2 Reading and Deserializing Data from a Sequential-Access File

The preceding section showed how to create a file for sequential access using object serialization. In this section, we discuss how to read serialized data sequentially from a file.

    The program in Fig. 14.20–Fig. 14.21 reads records from a file created by the program in Section 14.6.1 and displays the contents. The program opens the file for input by creating a FileInputStream object (line 21). The name of the file to open is specified as an argument to the FileInputStream constructor. In Fig. 14.18, we wrote objects to the file, using an ObjectOutputStream object. Data must be read from the file in the same format in which it was written. Therefore, we use an ObjectInputStream wrapped around a FileInputStream in this program (lines 20–21) If no exceptions occur when opening the file, variable input can be used to read objects from the file.

Fig. 14.20 Sequential file read using an ObjectInputStream.
     1   // Fig. 14.20: ReadSequentialFile.java
  2   // This program reads a file of objects sequentially
  3   // and displays each record.
  4   import java.io.EOFException;                    
  5   import java.io.FileInputStream;     
  6   import java.io.IOException;                         
  7   import java.io.ObjectInputStream;
  8     
  9   import com.deitel.jhtp6.ch14.AccountRecordSerializable;
   10     
   11  public class ReadSequentialFile
   12  {
   13   private ObjectInputStream input;
   14     
   15     // enable user to select file to open
   16     public void openFile()
   17     {
   18        try // open file
   19        {
   20 input = new ObjectInputStream(
   21            new FileInputStream( "clients.ser" ) );
   22        } // end try
   23        catch ( IOException ioException )
   24        {
   25           System.err.println( "Error opening file." );
   26        } // end catch
   27     } // end method openFile
   28     
   29     // read record from file
   30     public void readRecords()
   31     {
   32      AccountRecordSerializable record;
   33        System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
   34         "First Name", "Last Name", "Balance" );
   35     
   36        try // input the values from the file
   37        {
   38          while ( true )
   39           {
   40              record = ( AccountRecordSerializable ) input.readObject();
   41     
   42              // display record contents
   43              System.out.printf( "%-10d%-12s%-12s%10.2f\n",     
   44               record.getAccount(), record.getFirstName(),
   45               record.getLastName(), record.getBalance() );
   46           } // end while
   47       } // end try
   48        catch ( EOFException endOfFileException )
   49        {
   50           return; // end of file was reached
   51        } // end catch
   52        catch ( ClassNotFoundException classNotFoundException )
   53        {
   54           System.err.println( "Unable to create object." );
   55        } // end catch
   56        catch ( IOException ioException )
   57        {
   58           System.err.println( "Error during read from file." );
   59        } // end catch
   60     } // end method readRecords
   61     
   62   // close file and terminate application
   63  public void closeFile()
   64     {
   65        try // close file and exit
   66        {
   67           if ( input != null )
   68              input.close();
   69        } // end try
   70        catch ( IOException ioException )
   71        {
   72           System.err.println( "Error closing file." );
   73           System.exit( 1 );
   74        } // end catch
   75      } // end method closeFile
   76   } // end class ReadSequentialFile

Page 1 | 2 | 3 | 4 | 5 | 6 | 7

Tutorial Index