-6

What is the difference between FileInputStream and ByteArrayInputStream? When we should use them? What is the benefits of using one over other

1 Answers1

0

Streams

  1. byte oriented stream (8 bit)
  2. good for binary data such as a Java .class file, images etc.
  3. good for "machine-oriented"

Readers/Writers

  1. char (utf-16) oriented stream (16 bit)
  2. one character at a time
  3. good for text such as a Java source
  4. good for "human-oriented" data

Buffered

  1. many bytes/characters at a time
  2. always useful unless proven otherwise

Both ByteArrayInputStream and FileInputStream serve the same purpose i.e. reading binary data and both implement a common abstract superclass InputStream.So it is really tough find out a sharp contrast among the two.But common logic dictates that arrays are already present in the memory hence they can be accessed much faster as compared to files which are present in the file system. Also if you go through the documentation of the two classes you will find out that read function of ByteArrayInputStream cannot block whereas the read function in FileInputStream blocks if no input is yet available.

So if you are confused about what to use when then think about these :

  1. In what form my data is present, file or array?
  2. Is speed really a requirement? If it is, then go for ByteArray. But remember you cannot store too much information in ByteArray as they are present in the memory.
mhasan
  • 3,703
  • 1
  • 18
  • 37