// 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.*;
import java.util.*;

public class ObjectStreamFun {
    private String filename;
    public ObjectStreamFun(String filename) {
        this.filename = filename;
    }
    public void appendStringToFile() throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(filename, true);
        //virker ikke//ObjectOutputStream out = new ObjectOutputStream(fos);
        //start hack
        ObjectOutputStream out;
        File f = new File(filename);
        boolean append = f.exists() && (f.length() > 0);
        if(append) {
            out = new ObjectOutputStream(fos){
                protected void writeStreamHeader() throws IOException{}
            }; 
        } else {
            out = new ObjectOutputStream(fos);
        }
        //end hack
        String s = "test";
        out.writeObject(s);
        out.close();
        fos.close();
    }
    public ArrayList<String> readStringsFromFile() throws ClassNotFoundException, FileNotFoundException {
        ArrayList<String> list = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream in = null;
        try {
            in = new ObjectInputStream(fis);
            while (true) {
                list.add((String)in.readObject());
            }
        } 
        catch (IOException ex) { ex.printStackTrace(); }
        try {
            in.close();
            fis.close();
            File file = new File(filename);
            file.deleteOnExit();
        }
        catch (IOException ex) { ex.printStackTrace(); }
        return list;
    }
    public static void main(String[] args) throws Exception {
        ObjectStreamFun o = new ObjectStreamFun("C:\\test.ser");
        o.appendStringToFile();
        o.appendStringToFile();
        o.appendStringToFile();
        for(String s : o.readStringsFromFile()) {
            System.out.println(s);
        }
    }
}
