java - 通过 ObjectInputStream 反序列化时出现 StreamCorruptedException

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

最佳答案

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

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/

相关文章:

java - lucene 在服务断开之前不会调用操作

java - 在安装应用程序之前在 Android 手机中查找数据消息

java - 使用JSF将应用程序迁移到其他服务器

java - 尝试在 JAVA 中创建 Zip 文件时出现 java.util.zip.ZipException?

java - 什么是编程中的 vector (LibGDX)?

java - 它是一个正确的 JSON 文件吗?

java - WS-Federation 主动请求者配置文件 SOAP 请求

java - 如何适当限制对外部系统的Web请求?

java - 无法为GUI更改计算器创建“重置”按钮

java - 访问设置时间不确定的连接的模式/最佳实践