Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.

Similar presentations


Presentation on theme: "Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from."— Presentation transcript:

1 Object Serialization

2

3  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from a file, there’s no way to tell whether it came from an int, a String or a double.  We have only data, not type information, on a disk.  Sometimes we want to read an object from or write an object to a file or over a network connection.  Java provides object serialization for this purposes.

4 Object Serialization  A serialized object is an object represented as a sequence of bytes  It includes the object’s data  It includes object’s type  it includes types of data stored in the object  After a serialized object has been written into a file, it can be read from the file and deserialized  It includes the type information and bytes that represent the object  It includes its data can be used to recreate the object in memory.

5 ObjectOutputStream Class ObjectOutputStream public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants  An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream  Only objects that support the java.io.Serializable interface can be written to streams.  Entire objects can be written to a stream

6

7 OutputStream Class OutputStream  OutputStream is an abstract class from which all byte-oriented output streams are derived  Its descendant classes are used for general- purpose (non-character) output  These streams are aimed at writing groups of 8-bit bytes to output destinations  The bytes are in the same format as Java primitive types For example, 4-byte groups corresponding to type int can be written to a disk file

8 Class ObjectInputStream public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream Entire objects can be read from a stream.

9

10 InputStream  InputStream is an abstract class from which all byte-oriented input streams are derived  Its descendant classes are used for general- purpose (non-character input)  These streams are aimed at delivering data to a program in groups of 8-bit bytes.  The bytes can be grouped into the size necessary for the type of data For example, if a disk file contains 32-bit int data, data can be delivered to the program in 4-byte groups in the same format as Java primitive type int

11 Classes ObjectInputStream and ObjectOutputStream  To use serialization with files, we initialize ObjectInputStream and ObjectOutputStream objects with stream objects that read from and write to files.  Initializing stream objects with other stream objects is called wrapping  The new stream object being created wraps the stream object specified as a constructor argument.

12 Classes ObjectInputStream and ObjectOutputStream  Classes ObjectInputStream and ObjectOutputStream simply read and write the byte-based representation of objects  They don’t know where to read the bytes from or write them to.  The stream object that you pass to the ObjectInputStream constructor supplies the bytes that the ObjectInputStream converts into objects.  The stream object that you pass to the ObjectOutputStream constructor takes the byte-based representation of the object  ObjectOutputStream produces and writes the bytes to the specified destination (e.g., a file, a network connection, etc.).

13 Interface ObjectOutput  The ObjectOutput interface contains method writeObject  It takes an Object as an argument and writes its information to an OutputStream.  A class that implements interface ObjectOutput (such as ObjectOutputStream) declares this method and ensures that the object being output implements interface

14 Interface ObjectInput  The ObjectInput interface contains method readObject  It reads and returns a reference to an Object from an InputStream.  After an object has been read, its reference can be cast to the object’s actual type.  Applications that communicate via a networkncan also transmit objects across the network

15 Creating a Sequential-Access File Using Object Serialization  The object serialization is performed with byte-based streams  the sequential files created and manipulated will be binary files.  Binary files typically cannot be viewed in standard text editors.  We write a separate application that knows how to read and display serialized objects.  We begin by creating and writing serialized objects to a sequential-access file.

16 Object Serialization Example

17 // Serializable Account class for storing records as objects import java.io.Serializable; public class Account implements Serializable { private int account; private String firstName; private String lastName; private double balance;

18 // initializes an Account with default values public Account() { this(0, "", "", 0.0); } // call other constructor // initializes an Account with provided values public Account(int account, String firstName, String lastName, double balance) { this.account = account; this.firstName = firstName; this.lastName = lastName; this.balance = balance; } // set account number public void setAccount(int acct) { this.account = account; }

19 Defining Class Account  Class Account encapsulates the client record information used by the serialization examples.  All examples and class Account are located in the same directory  Class Account contains private instance variables account, firstName, lastName and balance and set and get methods for accessing these instance variables.  The set methods do not validate the data in this example  Because they should do so in an “industrial-strength” system.

20 Interface Serializable  Class Account implements interface Serializable  It allows objects of this class to be serialized and deserialized with ObjectOutputStreams and ObjectInputStreams  Interface Serializable is a tagging interface.  Such an interface does not contain methods.  A class that implements Serializable is tagged as being a Serializable object.  An ObjectOutputStream will not output an object unless it is a Serializable object  Any object of a class implements Serializable.

21 // get account number public int getAccount() { return account; } // set first name public void setFirstName(String firstName) { this.firstName = firstName; } // get first name public String getFirstName() { return firstName; }

22 // set last name public void setLastName(String lastName) { this.lastName = lastName; } // get last name public String getLastName() { return lastName; } // set balance public void setBalance(double balance) { this.balance = balance; } // get balance public double getBalance() { return balance; } } // end class Account

23  In a Serializable class, every instance variable must be Serializable.  Non-Serializable instance variables must be declared transient to indicate that they should be ignored during the serialization process.  All primitive-type variables are serializable.  For reference-type variables, we must check the class’s documentation (and possibly its superclasses) to ensure that the type is Serializable.  Strings are Serializable.  Arrays are serializable;  In a reference-type array, the referenced objects might not be.

24 Writing Serialized Objects to a Sequential-Access File  The code creates the sequential-access file  To open the file, we call Files static method newOutputStream,  It receives a Path specifying the file to open and, if the file exists, returns an OutputStream that can be used to write to the file.  Existing files that are opened for output in this manner are truncated.  There is no standard filename extension for files that store serialized objects, so we chose the.ser

25 // CreateSequentialFile.java // Writing objects sequentially to a file with class ObjectOutputStream import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.NoSuchElementException; import java.util.Scanner;

26 public class CreateSequentialFile { private static ObjectOutputStream output; // outputs data to file public static void main(String[] args) { openFile(); addRecords(); closeFile(); } public static void openFile() // open file clients.ser { try { output = new ObjectOutputStream( Files.newOutputStream(Paths.get("clients.ser") )); } catch (IOException ioException) { System.err.println("Error opening file. Terminating."); System.exit(1); // terminate the program }

27 public static void addRecords() // add records to file { Scanner input = new Scanner(System.in); System.out.printf("%s%n%s%n? ", "Enter number, first name, last name, balance.", "Enter end-of-file indicator to end input."); while (input.hasNext()) // loop until end-of-file indicator { try { // create new record; this example assumes valid input Account record = new Account(input.nextInt(), input.next(), input.next(), input.nextDouble()); // serialize record object into file output.writeObject(record); }

28 catch (NoSuchElementException elementException) { System.err.println("Invalid input. Please try again.") input.nextLine(); // discard input so user can try again } catch (IOException ioException) { System.err.println("Error writing to file. Terminating."); } System.out.print("? "); } //end of while }//end of method addRecords()

29 // close file and terminate application public static void closeFile() { try { if (output != null) output.close(); } catch (IOException ioException) { System.err.println("Error closing file. Terminating."); } } // end class CreateSequentialFile

30 Sequential file created using ObjectOutputStream. Enter number, first name, last name, balance. Enter end-of-file indicator to end input. ? 100 Bob Blue 24.98 ? 200 Steve Green -345.67 ? 300 Pam White 0.00 ? 400 Sam Red -42.16 ? 500 Sue Yellow 224.62 ? ^Z


Download ppt "Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from."

Similar presentations


Ads by Google