import java.io.*; import java.util.*; public class SerializationTest { public static void main(String[] args) throws IOException { if(args.length>0) { if("read".equals(args[0])) { read(); return; } if("write".equals(args[0])) { write(); return; } } System.out.println("Use either \"read\" or \"write\" as argument."); System.out.println("Delete SerializationTest$Foobar.class before \"read\" to test deserialization in absence of class."); } public static final String FILENAME="test.ser"; public static void write() throws IOException { File file=new File(FILENAME); System.out.println("Writing file "+file.getAbsolutePath()); FileOutputStream fos=new FileOutputStream(file); ObjectOutputStream oos=new ObjectOutputStream(fos); Serializable[] objects=new Serializable[]{ "Foo", new Foobar("The same string"), "The same string" }; for(Serializable current:objects) { oos.writeObject(current); } oos.close(); } public static void read() throws IOException { File file=new File(FILENAME); System.out.println("Reading file "+file.getAbsolutePath()); FileInputStream fis=new FileInputStream(file); ObjectInputStream ois=new ObjectInputStream(fis); List read=new ArrayList(); for(;;) { try { Object obj=ois.readObject(); read.add(obj); } catch(ClassNotFoundException ex) { ex.printStackTrace(); read.add(null); } catch(EOFException ex) { System.out.println(ex); break; } } System.out.println(read); ois.close(); } public static class Foobar implements Serializable { private String string; public Foobar() { this(null); } public Foobar(String string) { this.string=string; } public String toString() { return "Foobar[string="+string+"]"; } } }