我正在尝试测试一个程序,为此我需要访问 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();
}
最佳答案
显然,您正试图将同一个对象写入输出流两次:
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 ;-)
关于java - 通过 ObjectInputStream 反序列化时出现 StreamCorruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13347917/