我正在尝试测试一个程序,为此我需要访问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();
}
Run Code Online (Sandbox Code Playgroud)
显然,您正在尝试将两个相同的对象写入输出流:
out.writeObject(ss3);
ss3.writeExternal(out); // <-- Remove this!
Run Code Online (Sandbox Code Playgroud)
第二次写错误地使用了该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 ;-)
Run Code Online (Sandbox Code Playgroud)