1

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
  • Please post the Code of Chunk class Commented Oct 22, 2009 at 13:52
  • java.beans.XMLEncoder/XMLDecoder is an entirely separate mechanism. Commented Oct 22, 2009 at 14:08

3 Answers 3

2

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?
Sign up to request clarification or add additional context in comments.

1 Comment

Deserialization does not call constructors.
2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.