The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

your answer...

Posted by Ryan Fernandes on May 03, 2001 at 6:07 AM

Hi,
I've encountered the same problem.
I think I have the solution to it though:
Pasted below are 2 files that should give you an idea of how to tackle the situation.

Good luck.
Ryan
-----------------------------------------------------------


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:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us