Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Difference between Streams and I/O stream explained

I'm looking for a good explaination of the difference between the "new" Streams in Java 8 and the "old" I/O Streams we had before in Java 7. For someone without any knowledge of functional programming, it's hard to get that those are complete different things, especially because the names are the same. I get that the Stream API is something completely new and even revolutionary in some point, but in my naive thinking, in both cases we deal with sequences of "things", be it bytes, data or objects...

Can someone please offer a good explaination?

like image 882
codebat Avatar asked May 13 '26 18:05

codebat


2 Answers

It has nothing to do with each other and I agree, it's bad luck that IO Streams had their name before the "new" Streams have arrived. The I/O streams were meant as connections to external resources, mostly files, but also others. The new Streams are for functional programming and should be treated separately.

But you can actually use both concepts together. For example, a BufferedReader has a lines-method, which returns lines of a file (or other resources) as a Stream of Strings.

like image 172
Silverclaw Avatar answered May 16 '26 08:05

Silverclaw


Let's take a look at the picture illustrated I/O stream.

enter image description here

There are three concerning concepts related to I/O stream: Source, Destination, and Element (represented by the letter 'e'), where

  • Source or Destination could by a file, network connection, pipe, memory buffer etc.
  • An Element is just simply a piece of data and a stream consist of a chunk of elements

When to use what?

I/O streams are for reading content from a source, or writing the content to a destination. That's it, simple :-)

The new Stream concept introduced in Java 8 has nothing to do with I/O streams. Streams are not themselves data structures, but Classes that allow you to manipulate a collection of data in a declarative way (functional-style operation).

like image 44
Uvuvwevwevwe Avatar answered May 16 '26 07:05

Uvuvwevwevwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!