Typically, read(byte[] b) (or read(byte[] b, int off, int len)) is prefered than read(), because it might have some IO performance advantages.
And if you use read(byte[] b), BufferedInpurStream have no acutal advantages, as long as you use same buffer sizes.
void read(InputStream inputStream, int bufferSize) throws IOException
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = inputStream.read(buffer)) != -1)
{
// do some work
}
}
and
void read2(InputStream inputStream, int bufferSize) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(inputStream, bufferSize);
try
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = bis .read(buffer)) != -1)
{
// do some work
}
}
finally
{
bis.close();
}
}
try read and read2. you will find out that as long as you use appropriate buffer size, Wrapping to BufferedInputStream makes no performance improvements. (acutally it makes another computational costs...)
So, when do you need BufferedInputStream? Here is my suggest :
- If you know "appropriate" buffer size, just handle it directly. It produces shorter code. (ex: File reading. you can use file size as a buffer size.)
- If you don't know "appropriate" buffer size or you have to pass the InputStream to another library, wrap the stream as an BufferedInputStream. you may benefit from buffering. (ex: Web file transfer. server may not provide content-length field.)