Object Serialization. When the data was output to disk, certain information was lost, such as the...

30
Object Serialization

Transcript of Object Serialization. When the data was output to disk, certain information was lost, such as the...

Page 1: 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.

Object Serialization

Page 2: 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.
Page 3: 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.

Object SerializationWhen 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.

Page 4: 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.

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 deserializedIt includes the type information and bytes that

represent the object It includes its data can be used to recreate the object

in memory.

Page 5: 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.

Class ObjectOutputStreampublic 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

Page 6: 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.
Page 7: 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.

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) outputThese 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

Page 8: 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.

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.

Page 9: 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.
Page 10: 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.

InputStream InputStream is an abstract class from which all

byte-oriented input streams are derivedIts 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

Page 11: 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.

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 wrappingThe new stream object being created wraps the

stream object specified as a constructor argument.

Page 12: 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.

Classes ObjectInputStream and ObjectOutputStream

Classes ObjectInputStream and ObjectOutputStream simply read and write the byte-based representation of objectsThey 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.).

Page 13: 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.

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

Page 14: 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.

Interface ObjectInput The ObjectInput interface contains method

readObjectIt 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

Page 15: 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.

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.

Page 16: 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.

Object Serialization Example

Page 17: 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.

// 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;

Page 18: 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.

// 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; }

Page 19: 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.

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 exampleBecause they should do so in an “industrial-strength”

system.

Page 20: 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.

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 objectAny object of a class implements Serializable.

Page 21: 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.

// 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; }

Page 22: 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.

// 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

Page 23: 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.

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.

Page 24: 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.

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

Page 25: 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.

// 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;

Page 26: 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.

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 } }

Page 27: 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.

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); }

Page 28: 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.

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()

Page 29: 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.

// 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

Page 30: 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.

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