Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - Should I always wrap an InputStream as BufferedInputStream?

Does it make sense to always wrap an InputStream as BufferedInputStream, when I know whether the given InputStream is something other than buffered? For e.g:

InputStream is = API.getFromSomewhere()
if(!(is instanceof BufferedInputStream))
  return new BufferedInputStream(is);
return is;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does it make sense to always wrap an InputStream as BufferedInputStream, when I know whether the given InputStream is something other than buffered?

No.

It makes sense if you are likely to perform lots of small reads (one byte or a few bytes at a time), or if you want to use some of the higher level functionality offered by the buffered APIs; for example the BufferedReader.readLine() method.

However, if you are only going to perform large block reads using the read(byte[]) and / or read(byte[], int, int) methods, wrapping the InputStream in a BufferedInputStream does not help.

(In response to @Peter Tillman's comment on his own Answer, the block read use-cases definitely represent more than 0.1% of uses of InputStream classes!! However, he is correct in the sense that it is usually harmless to use a buffered API when you don't need to.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...