首页 > 解决方案 > Java用给定的ObjectOutputStream写一个字节数组

问题描述

我有一个带有自定义writeObject()readObject()方法的可序列化类。当一个对象序列化时,它需要一个接一个地写入两个字节数组。当某些东西对其进行反序列化时,它需要读取这两个数组。

这是我的代码:

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();
}

当对象被反序列化(readObject 方法)时,它会抛出一个EOFException并且所有三个变量都是null/undefined

关于问题标题,我看到了一个名为ByteArrayOutputStream的类,但要使用它,它必须包含在 ObjectOutputStream 中,这是我做不到的,我有一个 OutputStream 并且必须用它写。

1.如何使用objectOutputStream正确写入字节数组并使用ObjectInputStream正确读取?

2.为什么上面的代码连一个变量都没有读取就抛出EOFException ?

编辑:我需要澄清:在反序列化和序列化对象时,jvm 本身会调用readObject()writeObject() 。第二件事是,SignatureData 是 Sign 的子类,它来自第三方库——这就是它不可序列化的原因。

第三件事是,问题可能出在 ObjectInput/ObjectOutput 流的读写字节数组上,而不是在 Sign.SignatureData 类中。

标签: javaarraysserializationdeserializationeofexception

解决方案


推荐阅读