Xstream Tutorial
Xstream Tutorial
XStream is a simple Java-based library to serialize Java objects to XML and vice
versa.
This is a brief tutorial that adopts a simple and intuitive way to explain the basic
features of XStream library and how to use them.
Audience
This tutorial has been prepared to suit the requirements of Java developers who
would like to understand the basics of XStream library and use it in their Java
programs.
Prerequisites
Since XStream is a Java-based library, you need to have a clear understanding
of Java programming in order to make use of this library.
All the content and graphics published in this e-book are the property of
Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain,
copy, distribute or republish any contents or a part of contents of this e-book in
any manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial.
If you discover any errors on our website or in this tutorial, please notify us at
contact@tutorialspoint.com
i
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
1. OVERVIEW ............................................................................................................................ 1
Features .................................................................................................................................................... 1
4. ALIASING ............................................................................................................................. 14
5. ANNOTATIONS .................................................................................................................... 38
ii
6. CONVERTERS ...................................................................................................................... 44
iii
XStream
1. OVERVIEW
XStream is a simple Java-based library to serialize Java objects to XML and vice
versa.
Features
Easy to use - XStream API provides a high-level facade to simplify
common use cases.
Clean XML - XStream produces clean and compact XML output that is
easy to read.
Common Uses
Transport - XML is a text representation of object and can be used to
transport objects over the wire independent of the serialization /
deserialization techniques used.
Unit Tests - XStream API is JUnit compatible and can be used to enhance
unit testing of application modules.
2
XStream
2. ENVIRONMENT SETUP
Try the following example using the Try it option available at the top right
corner of the sample code on our website:
For most of the examples given in this tutorial, you will find a Try it option in our
website code sections at the top right corner that will take you to the online
compiler. So just make use of it and enjoy your learning.
http://www.oracle.com/technetwork/java/archive-139210.html
Follow the instructions to download Java and run the .exe to install Java on your
machine. Once you have installed Java on your machine, you would need to set
the environment variables to point to correct installation directories:
3
XStream
3. Alter the 'Path' variable so that it also contains the path to the Java
executable. For example, if the path is currently set to
'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
For example, if you use bash as your shell, then you would add the following line
at the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Notepad: On Windows, you can use any simple text editor like Notepad
(Recommended for this tutorial) or TextPad.
4
XStream
OS Archive name
Windows xstream-1.4.7.jar
Linux xstream-1.4.7.jar
Mac xstream-1.4.7.jar
OS Description
OS Description
export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-
Linux
1.4.7.jar:
export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-
Mac
1.4.7.jar:
5
XStream
3. FIRST APPLICATION
Before going into the details of the XStream library, let us see an application in
action. In this example, we've created Student and Address classes. We will
create a student object and then serialize it to an XML String. Then de-serialize
the same XML string to obtain the student object back.
File: XStreamTester.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
6
XStream
System.out.println(formatXml(xml));
student.setAddress(address);
return student;
}
serializer.setOutputProperty("{http://xml.apache.org/xslt}inde
nt-amount", "2");
7
XStream
class Student {
private String firstName;
private String lastName;
private int rollNo;
private String className;
private Address address;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
class Address {
private String area;
private String city;
private String state;
private String country;
private int pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String toString(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\nAddress [ ");
stringBuilder.append("\narea: ");
stringBuilder.append(area);
stringBuilder.append("\ncity: ");
stringBuilder.append(city);
stringBuilder.append("\nstate: ");
stringBuilder.append(state);
stringBuilder.append("\ncountry: ");
stringBuilder.append(country);
stringBuilder.append("\npincode: ");
stringBuilder.append(pincode);
stringBuilder.append(" ]");
return stringBuilder.toString();
}
}
C:\XStream_WORKSPACE>javac XStreamTester.java
C:\XStream_WORKSPACE>java XStreamTester
<rollNo>1</rollNo>
<className>1st</className>
<address>
<area>H.No. 16/3, Preet Vihar.</area>
<city>Delhi</city>
<state>Delhi</state>
<country>India</country>
<pincode>110012</pincode>
</address>
</Student>
Student [
firstName: Mahesh
lastName: Parashar
rollNo: 1
className: 1st
address:
Address [
area: H.No. 16/3, Preet Vihar.
city: Delhi
state: Delhi
country: India
pincode: 110012 ] ]
Steps to Remember
Following are the important steps to be considered here.
13
XStream
4. ALIASING
<student name="Suresh">
<note>
<title>first</title>
<description>My first assignment.</description>
</note>
<note>
<title>second</title>
<description>My second assignment.</description>
</note>
</student>
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
class Note {
private String title;
private String description;
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
15
XStream
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
}catch(Exception e){
return xml;
}
}
}
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
}
public List<Note> getNotes(){
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
17
XStream
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
In the above result, the Student object name is fully qualified. To replace it as
student tag, follow the next section.
18
XStream
Class Aliasing
Class aliasing is used to create an alias of a fully qualified name of a class in
XML. Let us modify our original example and add the following code to it.
xstream.alias("student", Student.class);
xstream.alias("note", Note.class);
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
19
XStream
xstream.alias("student", Student.class);
xstream.alias("note", Note.class);
Student student = tester.getStudentDetails();
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
}
20
XStream
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
}
public List<Note> getNotes(){
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Field Aliasing
Field aliasing is used to create an alias of a field in XML. Let us modify our
example again and add the following code to it.
File: XStreamTester.java
package com.tutorialspoint.xstream;
22
XStream
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
return student;
}
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
}catch(Exception e){
return xml;
}
}
}
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
24
XStream
}
public List<Note> getNotes(){
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
<note>
<title>first</title>
<description>My first assignment.</description>
</note>
<note>
<title>second</title>
<description>My Second assignment.</description>
</note>
</notes>
</student>
In the above result, we can see that the notes tag gets added as a list of notes.
To replace it, follow the next section.
xstream.addImplicitCollection(Student.class, "notes");
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
26
XStream
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
27
XStream
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
}
public List<Note> getNotes(){
return notes;
}
28
XStream
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
In the above result, we can see that name is coming as a child node and we
need it as an attribute of the root node. To replace it, follow the next section.
Attribute Aliasing
Attribute aliasing is used to serialize a member variable as an XML attribute. Let
us modify our example again and add the following code to it.
xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
30
XStream
import com.thoughtworks.xstream.io.xml.StaxDriver;
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
31
XStream
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
}
public List<Note> getNotes(){
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
32
XStream
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
Package Aliasing
Package aliasing is used to create an alias of a fully qualified name of a class in
XML to a new qualified name. Let us modify our example again and change the
following code.
xstream.alias("student", Student.class);
33
XStream
xstream.alias("note", Note.class);
xstream.aliasPackage("my.company.xstream","com.tutorialspoint.xstream");
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
xstream.addImplicitCollection(Student.class, "notes");
Student student = tester.getStudentDetails();
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
}
class Student {
private String studentName;
private List<Note> notes = new ArrayList<Note>();
public Student(String name) {
this.studentName = name;
}
public void addNote(Note note) {
notes.add(note);
}
public String getName(){
return studentName;
}
public List<Note> getNotes(){
return notes;
}
}
class Note {
private String title;
private String description;
public Note(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
37
XStream
5. ANNOTATIONS
xstream.alias("student", Student.class);
xstream.alias("note", Note.class);
xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
xstream.addImplicitCollection(Student.class, "notes");
The following code snippet illustrates the use of annotations to do the same
work in a much easier way.
38
XStream
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.io.xml.StaxDriver;
39
XStream
System.out.println(formatXml(xml));
}
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
}catch(Exception e){
return xml;
}
}
}
@XStreamAlias("student")
class Student {
40
XStream
@XStreamAlias("name")
@XStreamAsAttribute
private String studentName;
@XStreamImplicit
private List<Note> notes = new ArrayList<Note>();
@XStreamOmitField
private int type;
@XStreamAlias("note")
class Note {
private String title;
private String description;
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
<note>
<title>second</title>
<description>My Second assignment.</description>
</note>
</student>
xstream.processAnnotations(Student.class);
Or
xstream.autodetectAnnotations(true);
43
XStream
6. CONVERTERS
XStream converters are the key components of the XStream library, which are
responsible to convert an object to XML and vice versa. XStream provides
numerous converters for common types such as primitives, String, File,
Collections, arrays, and Dates.
Using Converter
Let us use a SingleValueConvertor whose purpose is to convert an object into a
single string. We will use SingleValueConvertor to write an object as attribute
string.
Create a Converter
Register a Converter
xstream.registerConverter(new NameConverter());
44
XStream
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.io.xml.StaxDriver;
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
}catch(Exception e){
return xml;
}
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
@XStreamAsAttribute
private Name studentName;
46
XStream
class Name {
private String firstName;
private String lastName;
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
48
XStream
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.io.xml.StaxDriver;
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
49
XStream
}catch(Exception e){
return xml;
}
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
@XStreamAsAttribute
private Name studentName;
class Name {
private String firstName;
private String lastName;
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
51
XStream
Custom Converter
XStream allows writing a converter from scratch, so that the developer can write
a completely new implementation on how to serialize an object to XML and vice
versa. A converter interface provides three methods:
52
XStream
}
}
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.StaxDriver;
53
XStream
serializer.setOutputProperty("{http://xml.apache.org/xslt}
indent-amount", "2");
Source xmlSource=new SAXSource(new InputSource(new
ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream())
.toByteArray());
}catch(Exception e){
return xml;
}
54
XStream
}
}
@XStreamAlias("student")
class Student {
@XStreamAlias("name")
private Name studentName;
class Name {
private String firstName;
private String lastName;
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
<name>Mahesh,Parashar</name>
</student>
57
XStream
7. OBJECT STREAMS
Syntax: reateObjectOutputStream()
ObjectOutputStream objectOutputStream =
xstream.createObjectOutputStream(new FileOutputStream("test.txt"));
Syntax: createObjectInputStream()
ObjectInputStream objectInputStream =
xstream.createObjectInputStream(new FileInputStream("test.txt"));
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.StaxDriver;
try {
ObjectOutputStream objectOutputStream =
xstream.createObjectOutputStream(new FileOutputStream("test.txt"));
objectOutputStream.writeObject(student1);
objectOutputStream.writeObject(student2);
objectOutputStream.writeObject(student3);
objectOutputStream.writeObject(student4);
objectOutputStream.writeObject("Hello World");
objectOutputStream.close();
ObjectInputStream objectInputStream =
xstream.createObjectInputStream(new FileInputStream("test.txt"));
Student student5 = (Student)objectInputStream.readObject();
Student student6 = (Student)objectInputStream.readObject();
Student student7 = (Student)objectInputStream.readObject();
Student student8 = (Student)objectInputStream.readObject();
String text = (String)objectInputStream.readObject();
System.out.println(student5);
System.out.println(student6);
System.out.println(student7);
System.out.println(student8);
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
59
XStream
e.printStackTrace();
}
}
}
@XStreamAlias("student")
class Student {
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
60
XStream
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
61
XStream
File: XStreamTester.java
package com.tutorialspoint.xstream;
import java.io.Writer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
62
XStream
System.out.println(xstream.toXML(student));
}
}
@XStreamAlias("student")
class Student {
}
}
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java
63
XStream
C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester
{
"firstName": "Mahesh",
"lastName": "Parashar"
}
64