I am serializing two objects to two different files.I then copy the first object into a third file and append the second object thus saving both objects into one single file.While copying I do not use readObject as I do not want to change the instance of the object just make a copy. When I read it again I use read object but it throws a exception.Why is an exception(StreamCorruptedException) being thrown?
The code used is shown below
import java.io.*;
import java.util.Date;
public class WriteCheck
{
public static void main(
String args[])
{
WriteCheck wc = new WriteCheck();
wc.write1();
wc.write2();
wc.copy();
wc.read();
}//main
public void write1()
{
try
{
FileOutputStream fos = new FileOutputStream( "Untitled1" );
ObjectOutputStream dos = new ObjectOutputStream(fos);
dos.writeObject(new Date());
dos.flush();
dos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}//write
public void write2()
{
try
{
FileOutputStream fos = new FileOutputStream( "Untitled2" );
ObjectOutputStream dos = new ObjectOutputStream(fos);
dos.writeObject(new Date());
dos.flush();
dos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}//write
public void copy()
{
try
{
FileOutputStream fos = new FileOutputStream( "Untitled3");
// ObjectOutputStream dos = new ObjectOutputStream(fos);
FileInputStream fis1 = new FileInputStream("Untitled1" );
byte[] buffer1 = new byte[4096];
int bytes1_read;
while((bytes1_read = fis1.read(buffer1))!=-1)
{
fos.write(buffer1,0,bytes1_read);
fos.flush();
}
fis1.close();
FileInputStream fis2 = new FileInputStream("Untitled2" );
byte[] buffer2 = new byte[4096];
int bytes2_read;
while((bytes2_read = fis2.read(buffer2))!=-1)
{
fos.write(buffer2,0,bytes2_read);
fos.flush();
}
fis2.close();
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}//copy
public void read()
{
try
{
FileInputStream fis = new FileInputStream("Untitled3" );
ObjectInputStream ios = new ObjectInputStream(fis);
ios.readObject();
ios.readObject();
ios.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}//read
}//writeCheck