Here I am creating a HashMap, adding it to a list, then serializing this list. Then closing the ObjectOutputStream and FileOutputStream. Then reopening the ObjectOutputStream and FileOutputStream and writing second list to it . While reading the file i am getting this error:
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1356)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at javaapplication27.NewMain4.main(NewMain4.java:60)
Java Result: 1
My code is this:
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("1", "A");
hm1.put("2", "B");
hm1.put("3", "C");
ArrayList al1 = new ArrayList();
al1.add(hm1);
HashMap<String, String> hm2 = new HashMap<String, String>();
hm2.put("4", "A1");
hm2.put("5", "B1");
hm2.put("6", "C1");
ArrayList al2 = new ArrayList();
al2.add(hm2);
FileOutputStream fos = new FileOutputStream("D:/sample.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al1);
oos.close(); // closing the sreams
fos.close();
fos = new FileOutputStream("D:/sample.ser", true);
oos = new ObjectOutputStream(fos);
oos.writeObject(al2);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream("D:/sample.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList al = (ArrayList) ois.readObject();
System.out.println("First: " + al);
al = (ArrayList) ois.readObject(); // This is line 60 in my code
System.out.println("Second: " + al);
- What is the reason for the error?
- What to do if I want to write two or more objects to a serialized file and read it back?
- What to do if I have to serialize the objects to the same file e.g.
sample.serfrom different Java classes, and read all the objects back?

