Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Buffers and streams, is this how they work?

 
Tarek Khojah
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now any given stream has a buffer, correct?

Most buffers aren't dynamic, so they can only hold a certain amount of bytes by default.

The buffer is just what holds the data *temporarily*.

So for example, I can't read the entire contents of a stream all at once, I can only read whatever is small enough to pass through the buffer.

Same with writing, I can't just write huge amounts of data in a single "write()" call, I need to use a while loop, always writing as little as one byte, or as big as the buffer's size, no more.

Same with read, I can't read the whole stream and save it somewhere, I can only read as much as a buffer's size at a given read() call.

Is that correct?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tarek Khojah:
Now any given stream has a buffer, correct?

No, not every stream absolutely needs to have a buffer. It's up to who implements the stream class, and it might not be necessary to have a buffer.
So for example, I can't read the entire contents of a stream all at once, I can only read whatever is small enough to pass through the buffer.

Same with writing, I can't just write huge amounts of data in a single "write()" call, I need to use a while loop, always writing as little as one byte, or as big as the buffer's size, no more.

Same with read, I can't read the whole stream and save it somewhere, I can only read as much as a buffer's size at a given read() call.

Is that correct?

Not really, the stream hides implementation details like how large its internal buffer is, if it has any. For example, the method OutputStream.write(byte[]) accepts a byte[] of any length. There's no restriction on the length of the byte[] you call it with because of the length of the buffer that the stream uses internally.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic