05 March 2010

Using java.beans.XMLEncoder and XMLDecoder

java.beans.XMLEncoder and java.beans.XMLDecoder provides functionality similar to one of java.io.ObjectInputStream and java.io.ObjectOutputStream in which it can serialize an Object ( or graph of Objects) to some streams to be used later.

I've created a simple example here on how to use it :

Here's the Person Class that to be serialized:

package org.daz.xml;

public class Person implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private int age;

// Don't forget the Default Constructor
public Person() {

public Person(String fName, String lName, int age) {
this.firstName = fName;
this.lastName = lName;
this.age = age;

public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public int getAge() {
return age;
public void setAge(int age) {
this.age = age;

And Here's The Encoder :

package org.daz.xml;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

public class XMLEncoderTest<T> {

private static final String FILE_PATH = "org/daz/xml/persons.xml";

public static void main(String[] args) throws Exception{
XMLEncoderTest<Person> personEncoder = new XMLEncoderTest<Person>();
Person person = new Person("Ahmed", "Talat", 23);
Person p = personEncoder.decode(true);
System.out.println("Result : ");
System.out.println(p.getFirstName() + " \t" + p.getLastName() + "\t" + p.getAge());

public void encode(T object) throws Exception{
OutputStream stream = new FileOutputStream(new File(XMLEncoderTest.class.getClassLoader().getResource(FILE_PATH).toURI()));
XMLEncoder encoder = new XMLEncoder(stream);

public T decode(boolean showXml) throws IOException{
InputStream inStream = XMLEncoderTest.class.getClassLoader().getResourceAsStream(FILE_PATH);
XMLDecoder decoder = new XMLDecoder(inStream);
T t = (T) decoder.readObject();

if (showXml) {
return t;

private void printXML()throws IOException{
InputStream inStream = XMLEncoderTest.class.getClassLoader().getResourceAsStream(FILE_PATH);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buf = new byte[inStream.available()];
System.out.println("Raw XML : \n" + byteStream.toString());

Before to run, create an empty xml file besides your Java source files (to be located at org/daz/xml/persons.xml )
Post a Comment