1

I have a serializable class with custom writeObject() and readObject() methods. When an object serializes, it needs to write two byte arrays, one after another. When something deserializes it, it needs to read those two arrays.

This is my code:

private void writeObject (final ObjectOutputStream out) throws IOException {
    ..
    out.writeByte(this.signature.getV());    //one byte
    out.writeObject(this.signature.getR());  //an array of bytes
    out.writeObject(this.signature.getS());  //an array of bytes
    out.close();
}

private void readObject (final ObjectInputStream in) throws IOException, ClassNotFoundException {
    ..
    v = in.readByte();
    r = (byte[])in.readObject();
    s = (byte[])in.readObject();
    this.signature = new Sign.SignatureData(v, r, s);    //creating a new object because
                                                         //sign.signaturedata
                                                         // is not serializable
    in.close();
}

When the object is being deserialized (readObject method) it throws an EOFException and all three variables are null/undefined.

Relating to question title, I saw a class called ByteArrayOutputStream, but to use it, it has to be enclosed in a ObjectOutputStream, which I cannot do, ad I have an OutputStream given and must write with it.

1. How do one properly write a byte array using objectOutputStream and properly reads it using ObjectInputStream?

2. Why the code above throws an EOFException without reading even one variable?

EDIT: I need to clarify: the readObject() and writeObject() are called by jvm itself while deserializing and serializing the object. The second thing is, the SignatureData is a subclass to Sign, that comes from a third-party library - and that's why it's not serializable.

The third thing is, the problem probably lies in the reading and writing byte arrays by ObjectInput/ObjectOutput streams, not in the Sign.SignatureData class.

Skelebot
  • 58
  • 9
  • 1
    Can you share the actual call of those methods? – Gaurav Srivastav Oct 05 '18 at 17:57
  • @Gaurav writeObject and readObject are called by jvm internally on the object of serialized class – nits.kk Oct 05 '18 at 18:34
  • But why they are privately defined? – Gaurav Srivastav Oct 05 '18 at 18:49
  • @GauravSrivastav, they must be private. There's [a SO question](https://stackoverflow.com/q/7467313/479288) with answers on why this is required. – Cos64 Oct 06 '18 at 04:37
  • *First*, don't close the streams in the serialization methods, because you didn't open them there. Leave it to the caller to do it. *Second*, I tried to reproduce your problem but it worked for me. Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Cos64 Oct 07 '18 at 05:06

0 Answers0