Moonlit
Moonlit

Reputation: 5409

Reading chunks of bytes from an InputStream

In my application I'am receiving a byte stream via Bluetooth. I am using DataInputStream to read a fixed amount of bytes at once from an input stream:

private final InputStream mInStream = ...
...
DataInputStream dataInputStream = new DataInputStream(mInStream);
...
while(true) {
... = dataInputStream.readFully(buffer,0,length);
}

Can i improve performance by wrapping mInStream in a BufferedInputStream and put this BufferedInputStream into DataInputStream? E.g.:

private final InputStream mInStream = ...
...
BufferedInputStream buffInStream = new BufferedInputStream(mInStream);
DataInputStream dataInputStream = new DataInputStream(buffInStream);
...
while(true) {
... = dataInputStream.readFully(buffer,0,length);
}

Will this gain performance? Or will it stay the same since i am reading a constant number of bytes from the inputstream?

thanks

Upvotes: 0

Views: 2834

Answers (1)

user207421
user207421

Reputation: 310840

Can i improve performance by wrapping mInStream in a BufferedInputStream and put this BufferedInputStream into DataInputStream?

It depends on how large the buffer you're reading into is. The default internal buffer of a BufferedInputStream is 8k bytes. If your own buffer is comparable to or larger than this, there is no advantage. If your buffer is say 128 or 256 bytes there almost certainly is.

... = dataInputStream.readFully(buffer,0,length);

readFully() doesn't return a value. You should only use this method when you're sure that you want exactly this many bytes, and that they should all be present in the input. If the remaining input is shorter than 'length it will throw EOFException and you will lose any data that has been partially read. If you're not sure how much data should be read you should use read(byte[]) or read(byte[], int, int).

Upvotes: 1

Related Questions