Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
cnSerialization.fm
Ser321 Class Notes
Ser321 Principles of Distributed Software Systems
2. Externalizing with Serialization
• Section 2.a Introduction to Serialization
• Section 2.b Basics of Java Execution
• Section 2.c Basics of Serialization with Java
• Section 2.d Customizing Java Serialization
• Section 2.e Multi-Language Compatible Serialization
• Section 2.f Serialization in C# with .NET
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 1
cnSerialization.fm
2.a.1
Ser321 Class Notes
2.a Introduction to Serialization
Motivation
• How can we save an instance of a user-defined class to a file for later use?
• How can we migrate an instance of a user-defined class across a network?
- Can the class definition and associated methods come with the object?
- If the class definition is already resident, how do we know it matches the
class definition on the remote host?
• What if the user-defined object contains information, such as a file handle,
that doesn’t make sense to transfer or we want a specific transfer format?
• Outcomes
- To be able to use the Java API interfaces, classes and methods involved
with Externalization and Serialization.
- To be able to move an instance from one Java virtual machine to another
via the network or a file. To be able to customize serialization.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 2
cnSerialization.fm
2.a.2
Ser321 Class Notes
Readings
• In Java Network Programming and Distributed ComputingText:
- Chapters 4, especially 4.5: Data Streams and Object Externalization,
Serialization
• In Java Network Programming 4th Edition Text:
- Chapter 2: Streams
• See also Java Serialization in the Java Tutorial
- Tutorial -> Essential Classes -> Basic I/O -> Object Streams
- http://java.sun.com/docs/books/tutorial/
• Json (JavaScript Object Notation). see:
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 3
cnSerialization.fm
2.a.3
Ser321 Class Notes
Index to Serialization Examples
• Serialize Group instance to a file: Section 2.c.3 Serializing Objects
• Java XML Serialization: Section 2.c.5 Serializing to XML
• JSON serialization: Section 2.c.7 JavaScript Object Notation
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 4
cnSerialization.fm
Ser321 Class Notes
2.b Basics of Java Execution
2.b.1 Java Virtual Machines
• Overview of JDK Compilation and Runtime Support.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 5
cnSerialization.fm
Ser321 Class Notes
2.b.2 Basic Elements of The Java Virtual Machine
• Functional elements of a JVM.
• Byte-code Verifier - examines the code found in .class files for illegal
pointer usage, data conversions, instructions and stack usage.
• Class Loader - determines how and when to load class files.
- Loads all classes needed to run a class,
- Protects system classes
• Security Manager monitors certain operations based on existing constraints
for accessing resources (files, ports, system).
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 6
cnSerialization.fm
Ser321 Class Notes
2.b.3 Java Runtime - Impact on Serialization
• Serialization of a Java object and subsequently de-serializing it into the same
or another executing Java program crosses the boundary of the java runtime
environment (the java command):
- The class of the object being serialized, must match in both the serializing
and deserializing programs.
- When serialization is used to pass objects among components of a
distributed application, situations can arise in which the de-serializing
program has not loaded a class (or subclass) of an object being deserialized.
- If a program attempts to de-serialize an object of a class for which no class
has been loaded, the runtime environment will search using the classpath
for a matching class. If found, the runtime will use the classloader (and
bytecode verifier) to load the class.
- Java Remote Method Invocation (RMI) provides an object-level
interface for distributing an application. Java RMI supports this type of
class loading when it receives a method parameter that is a sub-type of the
declared parameter type.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 7
cnSerialization.fm
Ser321 Class Notes
2.c Basics of Serialization with Java
2.c.1
Java Input and Output Streams
• Buffered Stream
java.io.BufferedOutputStream, and java.io.BufferedInputStream
- Buffered writing and reading single bytes (or arrays of bytes) to the output
stream or from the input stream. Data goes into an internal buffer, which
can be marked or reset. The implementation handles stream buffering.
• Data Stream
java.io.DataOutputStream, and java.io.DataOutputStream
- Lets an application write and read primitive Java data types (int,
boolean, double, char, ...) to/from a stream in a portable (machineindependent) way.
• Object Stream (built in support for externalizing Java Objects)
java.io.ObjectOutputStream, and java.io.ObjectInputStream
- Serializes and deserializes Java Objects and primitive types to/from a
stream. Object graphs (supports nesting of serializable objects) are
placed onto or obtained from a Stream. Only objects that support the
java.io.Serializable interface can be written to object streams.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 8
cnSerialization.fm
2.c.2
Ser321 Class Notes
Interface java.io.Serializable
• Instances of classes that implement the Serializable interface can be written
to, or read from a stream. No methods need to be implemented with the
Serializable interface. Its simply a marker indicating that language support
for serialization should be included. See the javadocs for Serializable.
• Stream-ifying a serializable object automatically includes stream-ifying all
of the (serializable) objects making up instance attributes of the object.
- Serialization places an object graph into a stream; all subordinate objects
are serialized.
- For example, suppose a Group object contains a Vector of User objects.
- Serializing the Group will automatically serialize all of the Vector,
including its User’s.
• All subtypes (classes that extend the class) of a serializable class are
themselves serializable.
• No methods are defined in the java.io.Serializable interface, so there are no
methods that need to be implemented to make your user-defined class
serializable.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 9
cnSerialization.fm
2.c.3
Ser321 Class Notes
Serializing Objects
• Example, Serializing an object - String “Today” to a file.
FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
• De-Serializing a string from a file.
FileInputStream in = new FileInputStream("theTime");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
• Different JVM’s communicate using serialized objects through:
- Files - see the example: GroupFileSerialize.java found in the sample
project groupSerialize.jar
- Sockets - see the section on Sockets.
- Remote Object Parameters - see the section covering RMI
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 10
cnSerialization.fm
2.c.4
Ser321 Class Notes
Object Serialization for User-Defined Classes
• implement java.io.Serializable (or Externalizable)
- No methods to implement
- Object (Input|Output) Stream takes care of serializing
• What gets serialized?
- Class and its signature (including serial version - see jdk tool:
serialver ser321.serialize.GroupImpl)
- Values of all non-transient and non-static members, including members
that refer to other objects
- Serialization “stream-ifies” a tree of serializable objects.
- In GroupFileSerialize.java, we serialize a GroupImpl, as well as its
included User objects. See: groupSerialize.jar
• What would you use the transient modifier for?
- fileHandles,
- Remote object references
- anything you don’t want serialized
- anything that doesn’t make sense in another java virtual machine
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 11
cnSerialization.fm
Ser321 Class Notes
2.d Customizing Java Serialization
2.d.1 Writing Objects in a Format you Design
• If your class implements Serializable, and provides readObject or
writeObject, it will be called during (de)serialization.
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// customized serialization code
}
- These are not in any interface but are used with Serializable
• To have complete control over serialization, implement the
java.io.Externalizable interface
- writeExternal and readExternal methods must be provided by the
implementing class.
- For Externalizable objects, only the identity of the object's class is
automatically saved by the stream.
- The class is responsible for writing and reading its contents, and it must
coordinate with any superclasses to do so.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 12
cnSerialization.fm
Ser321 Class Notes
2.d.2 Class Versioning
• Whenever you compile a Serializable class a Serial version is generated and
imprinted on each instance of the class
• When deserializing, the version of the object is compared with the version
of the class
- If .class version in JVM is not the one that created the object,
deserialization generates an exception
- Programmers may control the serialization version with:
static final long serialVersionUID=...
• How do you know the serialVersionUID of an older version of the class? The
JDK provides a tool to examine the serial version of a compiled class:
- serialver -classpath classes ser321.chat.ChatClientGui
- executing the serialver command will provide the full definition of the
serialVersionUID static field -- including its value. That value can be
explicitly specified by the programmer in subsequent versions of the class.
• A full explanation of the use of serialver and class compatibility is here:
https://docs.oracle.com/javase/8/docs/platform/serialization/spec/version.html#a6678
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 13
cnSerialization.fm
Ser321 Class Notes
2.e Multi-Language Compatible Serialization
2.e.1
Serialization Among Different Languages
• Inter-Language Serialization. What is it?
- Serialize an object of a class from one language (Java) and de-serialize
the object into a running program of another language (C++).
• Built-in Language Support? No languages support such inter-operability.
- Its not an easy problem. Object representation is dependent on the ObjectOriented programming language and not commonly specified. What
format and order are used to serialize an object and its parent classes?
- Even for primitive types (int, bool, double, for example), formats may be
different between languages (such as, how many bits, what precision).
• What formats support moving objects between running programs written in
different languages? The most accepted formats are text based.
- XML (Extensible Markup Language) https://www.w3.org/XML/
- SOAP (Simple Object Adapter Protocol) https://www.w3.org/TR/soap/
- Json (JavaScript Object Notation) see: http://json.org/
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 14
cnSerialization.fm
2.e.2
Ser321 Class Notes
JSON (JavaScript Object Notation) References
• JSON a popular text-based format for inter-language (de)serialization.
- JavaScript Object Notation Wikipedia page:
https://en.wikipedia.org/wiki/JSON
- JSON’s specification. See: http://json.org/
- Smile, a binary Json format at: http://wiki.fasterxml.com/SmileFormat
• JSON Implementations.
- See the list of implementations at:
http://www.json.org/
- C++ Json-cpp. Debian has a package for this implementation that can be
install using apt-get. Same for most package managers (MacOSX
MacPorts, for example).
https://github.com/open-source-parsers/jsoncpp
- Oracle Java Enterprise Edition (javax.json package)
http://www.oracle.com/technetwork/articles/java/json-1973242.html
- Douglas Crockford Implementation (distributed with Ser321 Examples):
https://github.com/eskatos/org.json-java
https://github.com/stleary/JSON-java
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 15
cnSerialization.fm
2.e.3
Ser321 Class Notes
JSON (JavaScript Object Notation) Values
• The basic JSON value types and there representations are:
- Asigned decimal number (compatible with floats, doubles and integers).
-125.32
- A string literal
“I am a string literal”
- A boolean value: can be either true or false
- An array of Json values denoted by encapsulating [ ] :
[ 122.55, “Another String”, [“A sub-array”,true], false ]
- A collection of named values (an Object), similar to a
Map<String,JSONObject> and encapsulated in { }
{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
- A null value, denoted as null
• Here is an example that serializes a Group to/from Java and C++ using the
implementations referenced above. See: groupJson.jar
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 16
cnSerialization.fm
2.e.4
Ser321 Class Notes
Serialization to XML
• The package java.beans supports serialization to XML for JavaBeans.
• What are JavaBeans?
- http://docs.oracle.com/javase/tutorial/javabeans/writing/index.html
- Or, http://en.wikipedia.org/wiki/JavaBeans
- JavaBeans are defined to enable reusable software components. A
JavaBean is a Java class that defines properties and “well-defined”
accessor and mutator functions for those properties.
- JavaBeans were defined to allow for reusable GUI components, although
they are now viewable or not. For example, when a newer version of a
GUI component wants to take advantage of (be compatible with) prior
release versions of those components, JavaBeans supports this reuse.
• The package java.beans provides facilities for managing JavaBeans.
- Among the facilities are an XMLEncoder and XMLDecoder which
object stream-ify a JavaBean using text-based XML.
• An example of Java XML serialization: See: userXml.jar
• The .NET framework has built-in XML and SOAP support. Covered next.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 17
cnSerialization.fm
Ser321 Class Notes
2.f Serialization in C# with .NET
2.f.1
Basics of Serialization in C#
• Converting the state of an object into a stream so that it can be persisted
or transported.
- Unlike Java, C# does not support transporting the code (class files).
• Serialization in .NET supports saving objects in binary, Soap, or XML.
• Binary and Soap Serialization of an object
- All properties and fields are serialized. Use binary when you wish to
replicate the object and transport or recover its entire state.
• XML Serialization of an object
- Only the public properties and fields are converted to the stream.
• Serialization involves using the Binary, Soap or XML formatter with
- Attributes [Serializable] and [NonSerialized]
- Possibly implementing the ISerializable interface, for customization.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 18
cnSerialization.fm
2.f.2
Ser321 Class Notes
Basics of Stream Input and Output in .NET System.IO
• Store and retrieve primitive data as binary values
- int, bool, string, byte, short, char, float, double, decimal
- use classes BinaryReader, and BinaryWriter
• See the example programs (with an Ant build file) in: streamIO.jar
- To read and write data to a binary file: BinaryRWExample.cs
• Store and retrieve primitive data as text values
- use classes StreamReader and StreamWriter to read and write files
- use classes StringReader and StringWriter to read/write a string buffer
• See the example program to read and write data to a text file:
- StreamRWExample.cs
• Directory and File information can be manipulated with the classes
- Directory, DirectoryInfo, File, FileInfo
- See the example program that lists the contents of a directory
- DirectoryInfoExample.cs
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 19
cnSerialization.fm
2.f.3
Ser321 Class Notes
Serializing an Object Graph
• Serializing an object serializes all related objects. See: serialABoat.jar
- All parents (which the child class extends) are serialized,
- All contained (fields or properties) are serialized.
• When an object of a derived class is serialized, each object up its inheritance
chain is able to write its state to the stream.
• When an object of a class is serialized, any properties which are objects are
able to write their state to the stream.
• Serializing a Sail object includes its Radio, Boat and any other parents.
length
draft
Boat
Document
is_a
keel
mast
Sail
has_a
Principles of Distributed Software Systems© T. Lindquist 2017
is_a
Radio
Report
frequency
state
January 2017
has_a
PrintRender
Page 20
cnSerialization.fm
2.f.4
Ser321 Class Notes
Marking Classes for Serialization
• Serializable Attribute
- SerializableAttribute class has a single parameterless constructor
- Attributing the class Document, as below indicates Document objects are
available for serialization.
• Mark transient properties with the NonSerialized attribute so they are not
serialized.
[Serializable]
public class Document : object {
[NonSerializable]
private FileStream fileHandle;
...
private int numberOfSections;
...
[NonSerializable]
private int docIDNumber
}
• Since the fileHandle has no meaning in a different process on a different
machine, this transient value should not be serialized.
• Although it could be, the class chooses not to serialize the docIDNumber.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 21
cnSerialization.fm
2.f.5
Ser321 Class Notes
Using the Formatter Classes
• System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
class used to serialize
- Create the stream to which the binary information is to be written
FileStream aStream = File.Create(fileName);
- Create the binary formatter object
BinaryFormatter aBinaryFormatter = new BinaryFormatter();
- Call the formatter’s serialize method
aBinaryFormatter.Serialize(aStream, aSailObject);
• Steps to deserialize an object from an binary document
- Create the stream from which the object will be read
FileStream aStream = File.OpenRead(fileName);
- Create a binary formatter object
BinaryFormatter aBinaryFormatter = new BinaryFormatter();
- Call the formatter’s deserialize method
Sail mySailObject = (Sail)aBinaryFormatter.Deserialize(aStream);
• There is also a Soap serialization formatter. See the class:
- System.Runtime.Serialization.Formatters.Soap.SoapFormatter
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 22
cnSerialization.fm
2.f.6
Ser321 Class Notes
Serialization to and from Xml
• The XmlSerializer only serializes the public properties of an object.
• Using System.Xml.Serialization.XmlSerializer class to serialize
- Use the XmlSerializer constructor to create an object to do the serializing
- Create an instance of the object to serialize and a stream to write the Xml
to (Stream, TextWriter or XmlWriter)
- Call the Serialize method to convert the object into an XML document.
• Steps to deserialize an object from an XML document
- Create a suitable object to read the document or stream (Stream,
TextWriter, or XmlWriter).
- Invoke the Deserialize method while casting the resulting object to the
type of the original object (that was serialized).
• Attributes controlling Xml Serialization
- [XmlIgnoreAttribute] - don’t serialize the public property that follows.
- [XmlAttribute] - serialize the class member as an attribute not an element
- [XmlRootAttribute("Sail",Namespace="http://pooh", IsNullable = false)]
- [XmlElementAttribute(IsNullable = false)] - no element if member is null
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 23
cnSerialization.fm
2.f.7
Ser321 Class Notes
XmlSerializer for IEnumerable or ICollection
• The XmlSerializer treats IEnumerable or ICollection classes differently.
• IEnumerable
- The class must have a public Item indexed property (indexer in C#) that
takes an integer, and it must have a public Count property of type integer.
- The class must implement a public Add method that takes a single
parameter and adds the argument value to the collection.
- The Add method’s parameter must be the same type as is returned from
the Item property, or one of that type's bases (the type returned from the
Current property on the value returned from GetEnumerator).
• ICollection
- For classes that implement ICollection, the values to be serialized are
retrieved using the Item property, not by calling GetEnumerator.
• Hashtables are not XmlSerializable because the Hashtable Item property
takes an object key.
- For example, several class examples use String keys.
- For examples of serialization see SerializeAHashtable.cs
in: serialEgs.jar
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 24
cnSerialization.fm
2.f.8
Ser321 Class Notes
Class Diagram for the Boat Example
• Sail inherits from Boat and includes a Radio property
public class Boat
public loa, beam, draft, name
private displacement, lengthWL
getName( ) --> string
dispOverLength( ) -- > double
public class Radio
is_a
public name
public class Sail : Boat
private isOn
public model
private sailArea
has_a
switchOnOff( ) --> void
isRadioOn( ) --> bool
getModel ( ) --> string
getSailArea( ) --> double
• See: serialABoat.jar
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 25
cnSerialization.fm
2.f.9
Ser321 Class Notes
Serializing Inherited and Nested Objects
• Here’s how to execute the project corresponding to the class diagram above
- Download and extract the archive
- Execute with either Ant or Nant; for example: ant execute
• Observations in reading the source code
- Sail, Boat and Radio classes are all marked as serializable
- All are serialized as a part of serializing a Sail object.
- Note that XMLSerializer serializes only public members (see sail.xml).
- In TestSerSail’s method writeXMLObject method, the constructor for
XmlSerializer only includes the type for Sail. Boat and Radio are detected
by the serializer.
- Suppose we want to XML serialize an ArrayList of Sail’s. We need:
XmlSerializer serializer = new XmlSerializer(typeof(ArrayList),
(new Type[]{(typeof(Sail))}));
- An ArrayList holds objects, and it does not cast to the most specific type.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 26
cnSerialization.fm
Ser321 Class Notes
2.f.10 Customizing Serialization
• You can provide your own functionality for serialization
- To filter the values of object properties as they are put into the stream or
recovered from the stream.
- For example if the object contains properties whose values are pathanmes,
you may want to convert relative paths into absolute paths.
- To control which properties (or components of properties) are saved and
subsequently restored.
• How to implement custom serialization
- Classes need to implement System.Runtime.Serialization.ISerializable
- ISerializable defines a single method
public virtual void GetObjectData(SerializationInfo si, StreamingContext ctx);
- GetObjectData is called once to make (key,value) associations for all
properties to be saved to the stream.
- Classes need to have a new constructor
public MyClassName (SerializationInfo si, StreamingContext ctx);
- Constructor recovers (deserializes) object properties from the stream
using the (key,value) associations.
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 27
cnSerialization.fm
Ser321 Class Notes
2.f.11 Custom Serialization of Nested Objects
• Example of Custom Serialization: see: CustomSerial.cs
• Xml serialization is designed to only work for public properties.
- You can serialize private properties using SOAP or Binary Serialization.
• The XmlSerializer does not call GetObjectData or the deserializing
constructor, so custom serialization only works for binary and SOAP.
- You cannot use customized serialization with the XmlSerializer to
serialize a Hashtable to XML.
• SerializationInfo class provides methods for GetObjectData and the
deserializing constructor to add/retrieve members to/from the stream.
- GetObjectData calls AddValue method to add primitives and
serializable Objects to the stream.
• To retrieve members from the stream, the deserializing constructor:
- Gets primitives and strings with methods: GetInt32, GetByte, GetString ...
- Gets nested objects using the method: GetValue(string, Type), which
causes the appropriate deserializing constructor to be called.
• Download both serialization examples with an Ant build file: serialEgs.jar
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 28
cnSerialization.fm
Ser321 Class Notes
2.f.12 Generating XML
• Often its necessary to generate XML without using pre-defined serialization
facilities
- When there are special XML formatting needs that built-in serialization
can not accommodate.
- Here are examples in both Java and C# programs showing how to use the
language’s XML facilities to write and read XML.
• The Java example (CourseTitles.java) shows how to generate XML by
using Java’s Reflection API, so that it could be made to work for any class
in general.
- See: generateXML.jar
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 29
cnSerialization.fm
2.g.1
Ser321 Class Notes
2.g Serialization in C++
Serialization is not supported as part of the Language
• Packages are available, such as:
- http://www.boost.org/doc/libs/1_56_0/libs/serialization/doc/tutorial.html
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 30
cnSerialization.fm
2.g.2
Ser321 Class Notes
Serialize Manually
• C++ provides limited support for file processing, which without the s11n
library must be used to accomplish serialization. C++ itself supports saving
only values of primitive types, such as short, int, char double. This can be
done by using either the C FILE structure or C++ fstream class.
• To save a value, use the fstream class. Here is an example:
#include <fstream>
#include <iostream>
using namespace std;
class Student{
public:
char FullName[40];
char CompleteAddress[120];
char Gender;
double Age;
bool LivesInASingleParentHome;
};
int main(){
Student one;
strcpy(one.FullName, "Ernestine Waller");
strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");
one.Gender = 'F';
one.Age = 16.50;
one.LivesInASingleParentHome = true;
ofstream ofs("fifthgrade.ros", ios::binary);
return 0;}
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 31
cnSerialization.fm
2.g.3
Ser321 Class Notes
Writing to the Stream
• The ios::binary option lets the compiler know how the value will be stored.
This declaration also initiates the file. To write the values to a stream, you
can call the fstream::write() method.
• After calling the write() method, you can write the value of the variable to
the medium. Here is an example:
#include <fstream>
#include <iostream>
using namespace std;
class Student{
public:
char FullName[40];
char CompleteAddress[120];
char Gender;double Age;
bool LivesInASingleParentHome;
};
int main(){
Student one;
strcpy(one.FullName, "Ernestine Waller");
strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");
one.Gender = 'F';
one.Age = 16.50;
one.LivesInASingleParentHome = true;
ofstream ofs("fifthgrade.ros", ios::binary);
ofs.write((char *)&one, sizeof(one));
return 0;
}
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 32
cnSerialization.fm
2.g.4
Ser321 Class Notes
Reading From the Stream
• Reading an object saved in binary format: call the ifstream::read() method.
#include <fstream>
#include <iostream>
using namespace std;
class Student{
public:
char FullName[40];
char CompleteAddress[120];
char Gender;
double Age;
bool LivesInASingleParentHome;
};
int main(){
/* First student
strcpy(one.FullName, "Ernestine Waller");
strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");
one.Gender = 'F';one.Age = 16.50;
one.LivesInASingleParentHome = true;
ofstream ofs("fifthgrade.ros", ios::binary);
ofs.write((char *)&one, sizeof(one));
/* Second student
ifstream ifs("fifthgrade.ros", ios::binary);
ifs.read((char *)&two, sizeof(two));
cout << "Student Information\n";
cout << "Student Name: " << two.FullName << endl;
cout << "Address:
" << two.CompleteAddress << endl;
cout << "Gender: “ << two.Gender << endl;
cout << "Age:
" << two.Age << endl;
cout << "Lives in a single parent home" << two.LivesInASingleParentHome << endl;
cout << "\n";
return 0;
}
Principles of Distributed Software Systems© T. Lindquist 2017
January 2017
Page 33