Someone explain to me what InputStream
and OutputStream
are?
I am confused about the use cases for both InputStream
and OutputStream
.
If you could also include a snippet of code to go along with your explanation, that would be great. Thanks!
Someone explain to me what InputStream
and OutputStream
are?
I am confused about the use cases for both InputStream
and OutputStream
.
If you could also include a snippet of code to go along with your explanation, that would be great. Thanks!
The goal of
InputStream
andOutputStream
is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is that you receive information from the stream (or send information into that stream.)InputStream
is used for many things that you read from.OutputStream
is used for many things that you write to.Here's some sample code. It assumes the
InputStream instr
andOutputStream osstr
have already been created:An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends
OutputStream is an abstract class that represents writing output. There are many different OutputStream classes, and they write out to certain things (like the screen, or Files, or byte arrays, or network connections, or etc). InputStream classes access the same things, but they read data in from them.
Here is a good basic example of using FileOutputStream and FileInputStream to write data to a file, then read it back in.
Stream: In laymen terms stream is data , most generic stream is binary representation of data.
Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.
Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .
From the Java Tutorial:
A stream is a sequence of data.
A program uses an input stream to read data from a source, one item at a time:
A program uses an output stream to write data to a destination, one item at time:
Sample code from oracle tutorial:
This program uses byte streams to copy xanadu.txt file to outagain.txt , by writing one byte at a time
Have a look at this SE question to know more details about advanced Character streams, which are wrappers on top of Byte Streams :
byte stream and character stream
you read from an InputStream and write to an OutputStream.
for example, say you want to copy a file. You would create a FileInputStream to read from the source file and a FileOutputStream to write to the new file.
If your data is a character stream, you could use a FileReader instead of an InputStream and a FileWriter instead of an OutputStream if you prefer.