serializable java arraylist code example

Example: how to serialize an arraylist in java

//Serialize and deserialize an ArrayList..
public class Serialize implements Serializable{
  	//Make sure you implement Serializable on all classes interacting with 
  	//serialize (class T in this case)
  	//Serialize an array to a file
  	FileOutputStream fos= new FileOutputStream("filePath.txt");
    ObjectOutputStream oos= new ObjectOutputStream(fos);
    oos.writeObject(arrayListToBeWritten);
    oos.close();
    fos.close();	//put try catch around both
  
  	//Deserialize an array from a file
	ArrayList<T> list;
    FileInputStream fis = new FileInputStream("filePath.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    list = (ArrayList) ois.readObject();	//Casting
    ois.close();
    fis.close();
  
  	for (T temp: list) {		//printing the array
            System.out.println(temp);
        }

Tags:

Java Example