1

我正在尝试测试一个程序,为此我需要访问 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();
        }
4

2 回答 2

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 ;-)
于 2012-11-12T17:17:12.653 回答
0

ss3.writeExternal(out);

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

out.writeObject(ss3);
于 2013-05-14T10:12:07.500 回答