0

I am trying to serialized an object to file and de-serialized it. If file is not present then this is first time object is written. If file is present then object was serialized before. How to append objects to serialized file?

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerilizationEx {
    public static void main(String[] args) throws IOException {
        ArrayList<String> list = new ArrayList<>();
        list.add("Allie");
        File file = new File("test.dat");
        if(!file.exists()) {
            try(FileOutputStream fos = new FileOutputStream(file);){
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(list);
            }
        } else {
            try(FileOutputStream fos = new FileOutputStream(file,true);){
                ObjectOutputStream oos = new ObjectOutputStream(fos) {
                    protected void writeStreamHeader() throws IOException {
                        reset();
                    }
                };
                oos.writeObject(list);
            }
        }
    }
}
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175

0 Answers0