import java.io.*;public class serial{
public static void main(String[] args) {
serialize(new obj("myString", "myString2", "myString3"));
serialize(new obj("myString1", "myString21", "myString31"));
serialize(new obj("myString2", "myString22", "myString32"));
deserialize();
}
public static void serialize(Object ob) {
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(ob);
byte[] barr = bos.toByteArray();
RandomAccessFile f = new RandomAccessFile("myObjects.ser", "rw");
long length = f.length();
f.seek( length );
f.writeInt(barr.length);
f.write(barr);
oos.flush();
oos.close();
f.close();
}
catch( Exception e ){
System.out.println("Exception :"+e);
}
}
public static void deserialize() {
try{
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
byte[] barr = null;
int intObjSize = 0;
Object ob = null;
RandomAccessFile f = new RandomAccessFile("myObjects.ser", "r");
for (;;) {
try{
intObjSize = f.readInt();
//read byte array from file
barr = new byte[intObjSize];
f.read(barr);
bis = new ByteArrayInputStream(barr);
ois = new ObjectInputStream(bis);
ob = ois.readObject();
System.out.println("Recovered "+((obj)ob).toString());
ois.close();
}
catch ( EOFException e ){
break;
}
finally{
//close streams..(too lazy to do it now)
}
}
}
catch( Exception e ){
System.out.println("Exception :"+e);
e.printStackTrace();
}
}
}
import java.io.*;public class obj implements Serializable{
String s1;
String s2;
String s3;
public obj(String s1, String s2, String s3) {
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
}
public String toString() {
return s1+":"+s2+":"+s3+System.getProperty("line.separator");
}
}
----------------------------------------------------------
> hi,
> I have opened a file in append mode
> using ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("filename",true));
> now my problem is that when i try to read the file using
> ObjectInputStream in =new ObjectInputStream(new
> FileInputStream("filename"));
> i get an error that
> java.io.StreamCorruptedException: Type code out of range, is -84
> what should i do?
>
> where am i going wrong.
Replies: