What is InputStream & Output Stream? Why and when do we use them?

Bohemian picture Bohemian · Dec 2, 2009 · Viewed 256.3k times · Source

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!

Answer

Chip Uni picture Chip Uni · Dec 2, 2009

The goal of InputStream and OutputStream 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 and OutputStream osstr have already been created:

int i;

while ((i = instr.read()) != -1) {
    osstr.write(i);
}

instr.close();
osstr.close();