Reputation: 21759
Why openInputStream
function doesn't return byte representation of the file instead of returning InputStream
which we have to iterate through and put it in ByteArrayOutputStream
?
Upvotes: 0
Views: 145
Reputation: 14165
An InputStream
is a different concept than a "byte representation of the file". You can actually get that from the stream, but most likely you don't want to.
A stream is an abstract concept of a queue of bytes, and is valid for a lot of things, not just files. By reading from an InputStream
you're actually reading the file's byte contents, but one by one to avoid wasting memory whn reading big files.
What you might be interested in, though, is memory mapping. Memory mapping allows you to map a portion of a file (or the whole file) directly into memory, so you can work directly with is.
Read more about Java's memory mapping here: http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html
Upvotes: 1
Reputation: 39477
The class InputStream is an abstract class, you cannot have an instance of it. Most such methods declare to return InputStream but actually return some real/concrete implementation of it. Then you can typically construct a higher-level stream (depending what your needs are) which accepts InputStream in its constructor as parameter. Now, you need ByteArrayOutputStream but somebody else might need something else as e.g. a FileInputStream. As the method returns InputStream, it can be useful to you both.
Upvotes: 1