aspose file tools*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes about object serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "about object serialization" Watch "about object serialization" New topic
Author

about object serialization

david hu
Ranch Hand

Joined: Jul 20, 2001
Posts: 143
Hi,
Can anyone help me look at the following code to help me find the problem? I wish to first write into a file two vectors,and then read it out from this file. But there's always a exception when I read the file.
The exception is:
ava.io.EOFException: Expecting code
at java.io.ObjectInputStream.peekCode(ObjectInputStream.java:1551)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:292)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:236)
at untitled8.Untitled1.<init>(Untitled1.java:39)
at untitled8.Untitled1.main(Untitled1.java:49)
--------------my code---------------------------------
import java.io.*;
import java.util.*;
public class Untitled1 {
public Untitled1() {
try{
FileOutputStream fo = new FileOutputStream("test1.txt");
ObjectOutputStream oos = new ObjectOutputStream(fo);
Vector[] aa = new Vector[2];
aa[0] = new Vector();
aa[1] = new Vector();
aa[0].add(new Integer(120));
aa[1].add(new Integer(111));
for(int i=0; i<aa.length; i++){
oos.writeObject(aa[i]);
}
oos.flush();
} catch(Exception e){e.printStackTrace();}
try{
FileInputStream fi = new FileInputStream("test1.txt");
ObjectInputStream oi = new ObjectInputStream(fi);
while(true){
Vector tmpv;
tmpv = (Vector)oi.readObject() ;
if (tmpv != null)
System.out.println(((Integer)tmpv.get(0)).intValue());
else break;
}
}catch(Exception e){e.printStackTrace();}
}
public static void main(String[] args){
Untitled1 aa = new Untitled1();
}
}
Philippe Maquet
Bartender

Joined: Jun 02, 2003
Posts: 1872
Hi david,
I didn't make any test, but from reading your code, it seems that you write the Vector contents, while you try to read the Vector itself.
Cheers,
Phil.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true.


Groovy
david hu
Ranch Hand

Joined: Jul 20, 2001
Posts: 143
How to make sure that my code doesn't exceed the boundary when I tried to read sequences of objects from a file?
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

catch OptionalDataException.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: about object serialization