ObjectInputStream.read(byte[], int, int) missing data?

只愿长相守 提交于 2019-12-25 02:34:08

问题


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
}

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/10442761/objectinputstream-readbyte-int-int-missing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!