通过ObjectInputStream反序列化时StreamCorruptedException

时间:2012-11-12 16:55:38

标签: java

我正在尝试测试一个程序,为此我需要访问ReadExternal函数,但我在ObjectInputStream上遇到StreamCorrupted异常。 我知道我需要使用WriteObject编写的对象,但不知道该怎么做......

ObjectOutputStream out=new ObjectOutputStream(new ByteArrayOutputStream());
    out.writeObject(ss3); 
    ss3.writeExternal(out);
    try{
         ByteInputStream bi=new ByteInputStream();
         bi.setBuf(bb);
         out.write(bb);
         ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bb));
         String s1=(String) in.readObject();
        }
        catch(Exception e){
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:6)

显然,您尝试将同一对象写入输出流两次:

out.writeObject(ss3); 
ss3.writeExternal(out); // <-- Remove this!

第二次写错误使用了writeExternal()方法,该方法永远不应该被明确调用,而是由ObjectOutputStream调用。

而且:out.write(bb);尝试将bb的内容写入ObjectOutputStream。这可能不是你想要的。

试试这样:

// Create a buffer for the data generated:
ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream out=new ObjectOutputStream( bos );

out.writeObject(ss3);

// This makes sure the stream is written completely ('flushed'):
out.close();

// Retrieve the raw data written through the ObjectOutputStream:
byte[] data = bos.toByteArray();

// Wrap the raw data in an ObjectInputStream to read from:
ByteArrayInputStream bis = new ByteArrayInputStream( data );
ObjectInputStream in = new ObjectInputStream( bis );

// Read object(s) re-created from the raw data:
SomeClass obj = (SomeClass) in.readObject();

assert obj.equals( ss3 ); // optional ;-)

答案 1 :(得分:0)

  

ss3.writeExternal(下);

您不应该直接调用该方法。你应该打电话

out.writeObject(ss3);