Skip to content

Serialize a ArrayList

2007 June 20
tags:
by Philippe Delodder

I needed to figure out an easy way to serialize and deserialize an arraylist with custom objects. Here below is the way i did it or you can download it here

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class XML {

public static void Serialize(ArrayList l){

try {FileOutputStream fos = new FileOutputStream("address.xml");

XMLEncoder xenc = new XMLEncoder(fos);xenc.writeObject(l);

xenc.close();fos.close();

} catch (FileNotFoundException e) {// TODO Auto-generated catch block

e.printStackTrace();} catch (IOException e) {

// TODO Auto-generated catch blocke.printStackTrace();

}}

public static ArrayList Deserialize(){

//		 Create input streams.

FileInputStream fis;

ArrayList List = new ArrayList();

try {

fis = new FileInputStream("address.xml");

XMLDecoder xdec = new XMLDecoder(fis);

//			Read object.

List = (ArrayList) xdec.readObject();

xdec.close();

fis.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return List;

}

}
One Response leave one →
  1. October 19, 2011

    Good post. Its realy good. Many info help me.

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

Bad Behavior has blocked 179 access attempts in the last 7 days.