user705414
user705414

Reputation: 21220

Can anyone explain the principle of BufferedInputStream?

When using BufferedOutputStream, I think the real output does not happen until we use flush? How about BufferedInputStream, is there flush method?

Upvotes: 3

Views: 1697

Answers (6)

Max
Max

Reputation: 1040

If you have a choice, always use the BufferedInputStream as it brings you the advantages already listed in this thread and also implements the .mark()- and .reset()-Method which allows you to "reuse" the stream (sort of).

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 62129

The real output in BufferedOutputStream happens either when the internal buffer is full, or when you flush.

With BufferedInputStream there is no flush, because it does not make sense.

What it does is to read into its internal buffer big chunks of data from the underlying stream, which is presumed to be expensive to call, and then efficiently give you little pieces of that data as you request them. As soon as you have read a bufferload of data, it automatically reads the next buffer for you from the underlying stream. So, its operation is entirely transparent to you.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533870

There is a read() from the OS whenever you need to read more data. There is no equivalent of flush().

The closest is in MemoryMappedByteBuffer where you can trigger a region to load before its needed.

Upvotes: 0

Raku
Raku

Reputation: 591

Flushing means that you write the complete contents of the buffer to your disk. This only makes sense when you're writing to the disk, but not when you're reading from it.

Some people might use "flush the buffer" in a reading context when they want to clear the buffer for some reason.

But I would call the write operation flush and the read operation clear in order to avoid confusion.

Terminology and precise speech is important while you're learning the basics. Try to acquire that habit. It'll help you a lot :)

Upvotes: 1

NPE
NPE

Reputation: 500893

The idea is that BufferedInputStream asks the underlying stream for data in relatively large chunks. The thinking is that requesting large blocks of data is more efficient than asking the OS for small amounts of data lots of times.

There is no flush method since it's not needed (there's no writing so there's nothing to flush).

Upvotes: 0

user1145202
user1145202

Reputation: 147

There's no flush method. Flush methods are just for output.

Upvotes: 1

Related Questions