views:

120

answers:

3

I have following code to serialize my data into a file:

out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(chunk);
out.flush();

I read with the following:

in = new ObjectInputStream(new FileInputStream(file));
Chunk chunk = (Chunk) in.readObject();

The weird thing is, when I read the data, all members are set to default and I get no data back that I wrote before.

If I use the XML variant all works fine.

e = new XMLEncoder(new FileOutputStream(file));
e.writeObject(chunk);
e.flush();

and

e = new XMLDecoder(new FileInputStream(file));
Chunk chunk = (Chunk) e.readObject();

What is wrong with the binary format?

Update

Ok i got this now: Chunk is a complex class with classes in, other classes with other classes in and so on. At some point the contained classes is declared as Object and should be Serializable. As Steve mentioned.

Thank you for your answers.

+2  A: 

The only reason I can think of for fields being set to default during serialization would be that they're defined as transient.

If that's not it, try distilling your code to a small, self-contained program that reproduces the problem. Most likely, you will spot the cause of the problem while you do that, otherwise post it here.

Michael Borgwardt
I was about to say that :D
Rakesh Juyal
+2  A: 

While I can't think of a good reason why one decoder would work differently than another, I'd suggest posting the code of the Chunk object. Things to look at:

  • Are you declaring any fields transient? These won't get serialized
  • Are any of the problems occurring with nested objects or collections which themselves may not be serializable?
  • Are the defaults overwritten in the constructor , or somewhere else that's not going to be called in a deserialization operation?
Steve B.
Deserialization does not call constructors.
Michael Borgwardt
yes - as written, "or somewhere ELSE that's not going to be called"...
Steve B.
A: 

Another (admittedly unlikely) possibility besides the obvious transient fields mentioned by others is that Chunk might implement Externalizable but not actually override the necessary writeExternal / readExternal methods. That would also explain why XMLEncoder works.

Jim P