Object Streams Tutorial
Transcript of Object Streams Tutorial
-
7/30/2019 Object Streams Tutorial
1/4
Object Streams TutorialXStream provides alternative implementations ofjava.io.ObjectInputStream and
java.io.ObjectOutputStream, allowing streams of objects to be serialized or deserialized from XML.
This is useful when processing large sets of objects, as only one needs to be in memory at a time.
Using the Object StreamsThe interface to the object streaming capabilities of XStream is through the standard
java.io.ObjectOutputStream andjava.io.ObjectInputStream objects.
ExampleTo serialize a stream of objects to XML:
ObjectOutputStream out = xstream.createObjectOutputStream(someWriter);
out.writeObject(new Person("Joe", "Walnes"));out.writeObject(new Person("Someone", "Else"));out.writeObject("hello");out.writeInt(12345);
out.close();The resulting XML:
JoeWalnes
SomeoneElse
hello123
To deserialze the stream of objects from the XML:
ObjectInputStream in = xstream.createObjectInputStream(someReader);
Person a = (Person)in.readObject();Person b = (Person)in.readObject();String c = (String)in.readObject();int d = in.readInt();
Considerations
http://xstream.codehaus.org/index.html -
7/30/2019 Object Streams Tutorial
2/4
Root nodeBecause an XML document can only have a single root node, all the serialized elements must be wrapped
in an additional root node. This root node defaults to , as shown in the example above.
This can be changed by using the overloaded method:
xstream.createObjectOutputStream(Writer writer, String rootNodeName);
Close the ObjectOutputStreamRemember to call ObjectOutputStream.close(), otherwise the stream will contain incomplete XML.
Detecting the end of the ObjectInputStreamWhen there are no more objects left to read in the stream, ObjectInputStream.readObject() (orprimitive equivalent) will throwjava.io.EOFException.
ReferencesNormally XStream will not know about references between the different objects that are written individually
in the ObjectStream. Nevertheless there is an example in the acceptance tests
(MultipleObjectsInOneStreamTest) where such a functionality is realized with the help of a custom
MarshallingStrategy. Note, that this implementation is not for general use, since it will ignore some
parameters at second invocation, but they do not matter in the demonstrated use case. Additionally those
references prevent the objects from being garbage collected, which is a bit counter-productive for the use
case of ObjectStreams as described above. So you have to know what you do!
Persistence API TutorialThe problemSuppose that you need a easy way to persist some objects in the file system. Not just one, but a whole
collection. The real problem arrives when you start using java.io api in order to create one output stream for
each object, showing itself to be really painful - although simple.
Imagine that you have the following Java class, a basic Author class (stolen from some other tutorial):
package com.thoughtworks.xstream;
public class Author {
private String name;public Author(String name) {
this.name = name;}public String getName() {
return name;}
}By using the XmlArrayList implementation of java.util.List you get an easy way to write all authors to disk
http://xstream.codehaus.org/index.html -
7/30/2019 Object Streams Tutorial
3/4
The XmlArrayList (and related collections) receives a StreamStrategy during its construction. This Strategy
decides what to do with each of it's elements. The basic implementation - our need - is the
FileStreamStrategy, capable of writing different files to a base directory.
// prepares the file strategy to directory /tmpStreamStrategy strategy = new FileStreamStrategy(new File("/tmp"));We can easily create an XmlArrayList from that strategy:
// prepares the file strategy to directory /tmpStreamStrategy strategy = new FileStreamStrategy(new File("/tmp"));// creates the list:List list = new XmlArrayList(strategy);
Adding elementsNow that we have an XmlArrayList object in our hands, we are able to add, remove and search for objects
as usual. Let's add five authors and play around with our list:
package org.codehaus.xstream.examples;
public class AddAuthors {
public static void main(String[] args) {
// prepares the file strategy to directory /tmpStreamStrategy strategy = new FileStreamStrategy(new
File("/tmp"));// creates the list:List list = new XmlArrayList(strategy);
// adds four authorslist.add(new Author("joe walnes"));list.add(new Author("joerg schaible"));list.add(new Author("mauro talevi"));list.add(new Author("guilherme silveira"));
// adding an extra authorAuthor mistake = new Author("mama");list.add(mistake);
}}If we check the /tmp directory, there are five files: 1.xml, 2.xml, 3.xml, 4.xml, 5.xml, each one containing the
XML serialized form of our authors.
Playing aroundLet's remove mama from the list and iterate over all authors:
package org.codehaus.xstream.examples;
public class RemoveMama {
public static void main(String[] args) {
// prepares the file strategy to directory /tmpStreamStrategy strategy = new FileStreamStrategy(new
File("/tmp"));
-
7/30/2019 Object Streams Tutorial
4/4
// looks up the list:List list = new XmlArrayList(strategy);
// remember the list is still there! the files 1-5.xml are still in /tmp!// the list was persisted!
for(Iterator it = list.iterator(); it.hasNext(); ) {Author author = (Author) it.next();if(author.getName().equals("mama")) {
System.out.println("Removing mama...");it.remove();
} else {System.out.println("Keeping " +
author.getName());}
}
}}The result?
Keeping joe walnesKeeping joerg schaibleKeeping mauro taleviKeeping guilherme silveiraRemoving mama...
Going furtherFrom this point on, you can implement different StreamStrategies in order to generate other behaviour using
your XmlArrayList collection, or try the other implementations: XmlSet and XmlMap.