Serialize a ArrayList
2007 June 20
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;
}
}
No comments yet