what is the difference in using InputStream instead of FileInputStream while creating the FileInputStream object

Mathan Kumar picture Mathan Kumar · Jul 8, 2013 · Viewed 28.3k times · Source

This may be a silly one, but I want to know the background operation difference.

  1. InputStream is = new FileInputStream(filepath);
  2. FileInputStream is = new FileInputStream(filepath);

What is the difference between the above two lines of code and in what scenarios are they used.

Answer

Jean Logeart picture Jean Logeart · Jul 8, 2013

FileInputStream extends InputStream: it is a specialized version of an InputStream designed for reading files.

There are several implementations of an InputStream according to the use of it.

It is usually good practice to use the highest type needed in your code. Therefore if your code needs to read data from an InputStream but not specifically from a FileInputStream, you should use InputStream. Yet if you do need to keep the information of your object being a FileInputStream and not just an InputStream, then you should keep the FileInputStream type.