0

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.

2
  • why are not you using loop if its work fine.its not necessary that it read all data at once Commented May 4, 2012 at 4:56
  • The loop works fine, I just wanted to know why the built-in method wasn't working. Also I suspect the appropriate method will be faster - it might be able to use native calls, etc. Commented May 6, 2012 at 3:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. The Google documentation is not only wrong but meaningless. It says it blocks until count bytes have been read without defining count. The Java Javadoc is correct.
Many (many) thanks! I've posted updated documentation at android-review.googlesource.com/#/c/36320.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.