serialize List - Java Collection Framework

Java examples for Collection Framework:List

Description

serialize List

Demo Code


import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main{
    public static <T> void serializList(List<T> collections, String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();/*from www . j  a  va 2 s  .c  o  m*/
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ObjectOutputStream objectOutputStream = null;
        try {
            OutputStream outputStream = new FileOutputStream(file, true);
            objectOutputStream = new ObjectOutputStream(outputStream);
            if (file.length() < 1) {
                objectOutputStream = new ObjectOutputStream(outputStream);
            } else {
                objectOutputStream = new MyObjectOutputStream(outputStream);
            }
            for (T collection : collections) {
                objectOutputStream.writeObject(collection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Related Tutorials