ObjectInputStream.read(字节[],INT,INT)丢失的数据? [英] ObjectInputStream.read(byte[], int, int) missing data?

查看:403
本文介绍了ObjectInputStream.read(字节[],INT,INT)丢失的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图序列化/反序列化的位图。在机器人如何保存位图 - 越野车code 是非常有益的。然而,当我去看过我的数组:

I'm trying to serialize/deserialize a bitmap. The answers at android how to save a bitmap - buggy code are very helpful. However, when I go to read my array:

private void readObject(ObjectInputStream in) throws IOException,
    ClassNotFoundException {
  int rowBytes = in.readInt();
  int height = in.readInt();
  int width = in.readInt();
  int bmSize = rowBytes * height;    // Ends up being 398208

  ByteBuffer byteBuffer = ByteBuffer.allocate(bmSize);
  int bytesRead = in.read(byteBuffer.array(), 0, bmSize);
  // Use array to create bitmap here
}

正在读1008个字节,而不是398208字节,我写的。我已经更换了一个循环,工作正常呼叫:

it is reading 1008 bytes, not the 398208 bytes that I wrote. I've replaced the call with a loop, which works fine:

for (int i = 0; i < bmSize; i++) {
  byteBuffer.array()[i] = in.readByte();
}

可能是什么回事?无异常。对于 ObjectInputStream.read的文档(字节[],INT,INT)表明它应及早回归的唯一原因是,如果它击中流,这显然不是因为我的工作围绕不抛出任何异常的结束。

What could be going wrong? No exception is thrown. The documentation for ObjectInputStream.read(byte[], int, int) indicates the only reason it should return early is if it hits the end of the stream, which clearly it isn't because my work-around doesn't throw any exceptions.

推荐答案

该文档是错误的。 ObjectInputStream的只是调用的InputStream读取的字节数。如果你想让它阻塞,直到数据被读取使用的readFully。

The documentation is wrong. ObjectInputStream just calls inputStream to read the bytes. Use readFully if you want it to block until the data is read.

这篇关于ObjectInputStream.read(字节[],INT,INT)丢失的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆