Search code examples
javaoptimizationfile-ioinputstreambytearrayinputstream

Is ByteArrayInputStream really a stream?


Point A >> It is possible to read the complete file in a single call in Java and store the data in-memory and do-processing. It applicable for smaller-sized files. Fine!

Point B >> When it comes to very large files, we need to do some sort of optimization to not hit up the memory overflow. Hence the IOStream exist whose name itself convey it is a Stream.

Point C >> Read some portion of data and do some processing. Read some more and forget about the data from previous read and do something on current read and so - on... which defines the data is streaming.

I see a confusion between the standard definition of the Streaming concept from point C (and) the existence of ByteArrayInputStream.

Question 1 : With ByteArrayInputStream, I have to initialise the stream with the entire data (using byte[]) I ALREADY have in-memory. Why then, it is a subclass of InputStream in first place? because it stream's nothing.

Question 2 : Why does the JavaDoc say something about buffering for ByteArrayInputStream. Where does it get applied?

Sorry, If my understanding is bad. I didn't get related answers for such narrowed questions online.

Can someone help here?


Solution

  • Because, to the user of the class, a ByteArrayInputStream behaves like a stream, i.e. it has the same interface.

    More generally, you should think of a stream as something that has a certain interface, not as something that is used for a certain purpose.

    The same is true, for example, for ArrayList which behaves like a List but, internally, is an array, which means that, unlike (for example) a LinkedList it has constant random access times.