Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java - How To Serialize and Deserialize objects

800308Nov 27 2007 — edited Nov 28 2007
Howdy,

I didn't find a "decent example" of serialization.

I wrote a wee generic Serializer and Deserializer.
* SerializerTest uses AccountParser to sax-parse "accounts.xml" into a List of AccountTO. Then it Serializes the objects using the "generic" Serializer into "accounts.ser".
* DeserializerTest uses the "generic" Deserializer to read "accounts.ser" back into a List. Then it prints the accounts back to standard out, in xml element format.
* AccountParser has it's own mainline.

Be warned this is not production ready code. It was hacked up in one night by a serialization newbie. I hope it proves useful to someone as example of how to serialize and deserialize objects. The code is 1.6. It uses generics. I use the xerces SAX parser.

-----
krc/utilz/io/Serializer.java
package krc.utilz.io;

import java.io.Serializable;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.List;

public class Serializer<T>
{
  private ObjectOutputStream out;

  public Serializer(OutputStream outputStream) {
    try {
      this.out = new ObjectOutputStream(outputStream);
    } catch (IOException e) {
      throw new RuntimeIOException(e.getMessage(), e);
    }
  }

  public void write(T record) {
    try {
      this.out.writeObject(record);
    } catch (IOException e) {
      throw new RuntimeIOException(e.getMessage(), e);
    }
  }

  public void write(List<T> records) {
    for(T record : records) {
      this.write(record);
    }
  }

}
-----
krc/utilz/io/test/SerializerTest.java
package krc.utilz.io.test;

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.List;
import java.util.ArrayList;

import krc.utilz.io.Serializer;

public class SerializerTest {

  public static void main(String[] args) {
    String infile = (args.length>0 ? args[0] : "C:/Java/home/src/krc/utilz/io/test/accounts.xml");
    String outfile = (args.length>1 ? args[1] : "C:/Java/home/src/krc/utilz/io/test/accounts.ser");
    try {
      InputStream inputStream = new FileInputStream(new File(infile));
      List<AccountT0> accounts = new AccountParser().parse(inputStream);
      Serializer<AccountT0> serializer = new Serializer<AccountT0>(new FileOutputStream(outfile));
      serializer.write(accounts);
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

}
-----
krc/utilz/io/test/AccountParser.java
package krc.utilz.io.test;

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;

import java.util.List;
import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

import krc.utilz.io.Filez;
import krc.utilz.io.RuntimeParserException;

public class AccountParser extends DefaultHandler
{
  private List<AccountT0> accounts = null;

  public AccountParser() {
  }

  public List<AccountT0> parse(InputStream xml) {
    try {
      SAXParserFactory factory = SAXParserFactory.newInstance(); //non-validating
      SAXParser parser = factory.newSAXParser();
      accounts = new ArrayList<AccountT0>();
      parser.parse(xml, (DefaultHandler)this);
      return(accounts);
    } catch (RuntimeParserException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeParserException(e.toString(), e);
    }
  }

  public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attributes) throws SAXException {
    if (qualifiedName.equals("account")) {
      processAccountElement(attributes);
    }
  }

  private void processAccountElement(Attributes attributes) {
    if (attributes == null) return;
    int id = 0;
    String firstName = null;
    String lastName = null;
    double balance = 0.0D;
    try {
      for (int i=0; i<attributes.getLength(); i++) {
        String attrName = attributes.getQName(i);
        if(attrName.equals("id")) {
          id = Integer.parseInt(attributes.getValue(i));
        } else if(attrName.equals("firstName")) {
          firstName = attributes.getValue(i);
        } else if(attrName.equals("lastName")) {
          lastName = attributes.getValue(i);
        } else if(attrName.equals("balance")) {
          balance = Double.parseDouble(attributes.getValue(i));
        }
      }
      this.accounts.add(new AccountT0(id, firstName, lastName, balance));
    } catch (Exception e) {
      throw new RuntimeParserException(e.toString(), e);
    }
  }

  //===========================================================
  // Test Harness
  //===========================================================

  public static void main(String[] args) {
    InputStream inputStream = null;
    try {
      String filename = (args.length>0 ? args[0] : "C:/Java/home/src/krc/utilz/io/test/accounts.xml");
      inputStream = new FileInputStream(new File(filename));
      List<AccountT0> accounts = new AccountParser().parse(inputStream);
      for (AccountT0 account : accounts) {
        System.out.println(account);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      Filez.close(inputStream);
    }
  }

}
-----
krc/utilz/io/Deserializer.java
package krc.utilz.io;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.IOException;

import java.util.List;
import java.util.ArrayList;

import krc.utilz.io.Filez;

public class Deserializer<T>
{

  @SuppressWarnings(value = "unchecked")
  public List<T> read(InputStream inputStream) {
    ObjectInputStream input = null;
    List<T> records = null;
    try { 
      input = new ObjectInputStream(inputStream);
      records = new ArrayList<T>();
      while (true) {
        records.add((T)input.readObject()); // warning: [unchecked] unchecked cast
      }
    } catch (EOFException eaten) {
      return(records);
    } catch (Exception e) {
      throw new RuntimeParserException(e.toString(), e);
    } finally {
      Filez.close(input);
    }
  }

}
-----
krc/utilz/io/DeserializerTest.java
package krc.utilz.io.test;

import java.util.List;
import java.io.InputStream;
import java.io.FileInputStream;

import krc.utilz.io.Deserializer;
import krc.utilz.io.Filez;

public class DeserializerTest {

  public static void main(String[] args) {
    InputStream inputStream = null;
    try {
      inputStream = new FileInputStream(args.length>0 ? args[0] : "C:/Java/home/src/krc/utilz/io/test/accounts.ser");
      List<AccountT0> accounts = (new Deserializer<AccountT0>()).read(inputStream);
      for (AccountT0 account : accounts) {
        System.out.println(account);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      Filez.close(inputStream);
    }
  }

}
-----
krc/utilz/io/Filez.java
package krc.utilz.io;

public abstract class Filez
{
  ... other methods omitted for brevity ...
  /**
   * close these "streams"
   * @param Closeable... "streams" to close.
   */
  public static void close(Closeable... streams) {
    Exception x = null;
    for(Closeable stream : streams) {
      if(stream==null) continue;
      try {
        stream.close();
      } catch (Exception e) {
        if(x!=null)x.printStackTrace();
        x = e;
      }
    }
    if(x!=null) throw new RuntimeIOException(x.getMessage(), x);
  }
-----
krc/utilz/io/RuntimeIOException
package krc.utilz.io;

public class RuntimeIOException extends RuntimeException {
  public static final long serialVersionUID = 4534250787L;
  public RuntimeIOException() { super(); }
  public RuntimeIOException(String message) { super(message); }
  public RuntimeIOException(String message, Throwable cause) { super(message, cause); }
  public RuntimeIOException(Throwable cause) { super(cause); }
}
-----
krc/utilz/io/RuntimeParserException
package krc.utilz.io;

public class RuntimeParserException extends RuntimeException {
  public static final long serialVersionUID = 1L;
  public RuntimeParserException() { super(); }
  public RuntimeParserException(String message) { super(message); }
  public RuntimeParserException(String message, Throwable cause) { super(message, cause); }
  public RuntimeParserException(Throwable cause) { super(cause); }
}
-----
krc/utilz/io/test/AccountTO.java
package krc.utilz.io.test;

public class AccountT0 implements java.io.Serializable
{
  private static final long serialVersionUID = 1L;

  private final long id;
  private final String firstName;
  private final String lastName;
  private final double balance;

  public AccountT0(long id, String firstName, String lastName, double balance) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.balance = balance;
  }

  public long getId() { return this.id; }
  public String getFirstName() { return this.firstName; }
  public String getLastName() { return this.lastName; }
  public double getBalance() { return this.balance; }

  public String toString() {
    return String.format("<account id=\"%s\" firstName=\"%s\" lastName=\"%s\" balance=\"%s\" />", id, firstName, lastName, balance);
  }

}
Cheers. Keith.

Edited by: corlettk on Nov 27, 2007 2:43 PM

BTW - I'd of course be open to suggestions on who this could be done better... but that really wasn't the point of this post. I'm hoping that Google with make it useful to newbies.

Edited by: corlettk on Nov 27, 2007 2:44 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 26 2007
Added on Nov 27 2007
2 comments
2,464 views