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

Viewed 272038

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!

10 Answers

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 .

For one kind of InputStream, you can think of it as a "representation" of a data source, like a file. For example:

FileInputStream fileInputStream = new FileInputStream("/path/to/file/abc.txt");

fileInputStream represents the data in this path, which you can use read method to read bytes from the file.

For the other kind of InputStream, they take in another inputStream and do further processing, like decompression. For example:

GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);

gzipInputStream will treat the fileInputStream as a compressed data source. When you use the read(buffer, 0, buffer.length) method, it will decompress part of the gzip file into the buffer you provide.

The reason why we use InputStream because as the data in the source becomes larger and larger, say we have 500GB data in the source file, we don't want to hold everything in the memory (expensive machine; not friendly for GC allocation), and we want to get some result faster (reading the whole file may take a long time).

The same thing for OutputStream. We can start moving some result to the destination without waiting for the whole thing to finish, plus less memory consumption.

If you want more explanations and examples, you have check these summaries: InputStream, OutputStream, How To Use InputStream, How To Use OutputStream

In continue to the great other answers, in my simple words:

Stream - like mentioned @Sher Mohammad is data.

Input stream - for example is to get input – data – from the file. The case is when I have a file (the user upload a file – input) – and I want to read what we have there.

Output Stream – is the vice versa. For example – you are generating an excel file, and output it to some place.

The “how to write” to the file, is defined at the sender (the excel workbook class) not at the file output stream.

See here example in this context.

try (OutputStream fileOut = new FileOutputStream("xssf-align.xlsx")) {
    wb.write(fileOut);
}
wb.close();
Related