// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SaveAndLoad {
    private static final String FNM = "C:\\test.dat";
    public static void test1() throws FileNotFoundException, IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FNM));
        oos.writeObject("A");
        oos.writeObject("BB");
        oos.writeObject("CCC");
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FNM));
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        ois.close();
    }
    public static void save2(Object o) throws FileNotFoundException, IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FNM, true));
        oos.writeObject(o);
        oos.close();
    }
    public static void test2() throws FileNotFoundException, IOException, ClassNotFoundException {
        save2("A");
        save2("BB");
        save2("CCC");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FNM));
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        ois.close();
    }
    public static void save3(Object o) throws FileNotFoundException, IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FNM));
        ArrayList<Object> lst = (ArrayList<Object>) ois.readObject();
        ois.close();
        lst.add(o);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FNM));
        oos.writeObject(lst);
        oos.close();
    }
    public static void test3() throws FileNotFoundException, IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FNM));
        oos.writeObject(new ArrayList<String>());
        oos.close();
        save3("A");
        save3("BB");
        save3("CCC");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FNM));
        ArrayList<Object> lst = (ArrayList<Object>) ois.readObject();
        ois.close();
        System.out.println(lst.get(0));
        System.out.println(lst.get(1));
        System.out.println(lst.get(2));
    }
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        test1();
        test2();
        test3();
    }
}
