5

I have an array byte[] arr;

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] arr = out.toByteArray();

How can I measure the data size in arr (if it was written to disk or transferred via network)? Are below approaches are correct - they suppose that sizeof(byte) = 1B

int byteCount = out.size();
int byteMsgCount = arr.length;

1 Answer 1

16

Yes, by definition the size of a variable of type byte is one byte. So the length of your array is indeed array.length bytes.

out.size() will give you the same value, i.e. the number of bytes that you wrote into the output stream.

[Edit] From cricket_007 comment: if you look at the implementation of size and toByteArray

public synchronized byte toByteArray()[] {
    return Arrays.copyOf(buf, count);
}

public synchronized int size() {
    return count;
}

... so toByteArray basically copies the current output buffer, up to count bytes. So using size is a better solution.

1
  • 2
    If you inspect the source code for toByteArray(), it will return a new array up to the value of the return value of size(), so unless the array is needed, then size() would be the preferred method call. Apr 12, 2016 at 21:11

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.