To serialize objects and data you perform the following steps:
Open an output stream of type java.io.OutputStream or a subclass of it.
Invoke the writeObject method to serialize objects or the appropriate write method to serialize primitive-type data (see the API documentation for the java.io.DataOutput interface for a list of primitive-data serialization methods).
Close the OutputStream and the NSXMLOutputStream.
Listing 2-1 shows an example of a method that serializes an object and an integer value.
Listing 2-1 Example of a serialization method
/** |
* Serializes an object and an integer. |
*/ |
public void serialize() { |
// Filename of the output file. |
String filename = "/tmp/example.xml"; |
try { |
// Create a stream to the output file. |
FileOutputStream output_stream = new FileOutputStream(filename); |
// Create an XML-output stream. |
NSXMLOutputStream xml_stream = new NSXMLOutputStream(output_stream); |
// Write the data. |
xml_stream.writeObject("Hello, World!"); |
xml_stream.writeInt(5); |
// Close the streams. |
xml_stream.flush(); // not really needed, but doesn't hurt |
xml_stream.close(); |
output_stream.close(); |
} |
catch (IOException e) { |
e.printStackTrace(); |
} |
} |
When an object is serialized, all the objects it refers to are also serialized. But this brings up the issue of cyclic references or multiple references to the same object. The problem is addressed by uniquely identifying each object as it is serialized. As each object is written to the output stream, its id attribute is set to a number that is unique within the XML document being generated. References to previously serialized objects use those objects' identification numbers instead of writing additional copies of them. This method is also used by object instances when referring to their class descriptions. See “Serializing Custom Objects to an XML Document” for an example.
Last updated: 2005-08-11