VOOZH about

URL: https://www.geeksforgeeks.org/java/difference-between-fileinputstream-and-objectinputstream-in-java/

⇱ Difference Between FileInputStream and ObjectInputStream in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Difference Between FileInputStream and ObjectInputStream in Java

Last Updated : 19 Jul, 2022

FileInputStream class extracts input bytes from a file in a file system. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. It should be used to read byte-oriented data for example to read audio, video, images, etc. The hierarchy of classes to deal with Input streams is as follows:

👁 Image
Hierarchy of classes to deal with Input streams

Example 1:

Output :

Java was called Oak at the beginning.

Now dwelling onto the output stream that is ObjectInputStream is used for deserializing primitive data and objects previously written using an ObjectOutputStream. Only objects that support the java.io.Externalizable interface can be read from streams. The Java ObjectInputStream class enables you to read Java objects from an InputStream instead of just raw bytes. You wrap an InputStream in an ObjectInputStream and so that you can read objects from it. Of course, the bytes read must represent a valid, serialized Java object. Otherwise, reading objects will fail. Normally we will use the ObjectInputStream to read data objects written(serialized) by a Java ObjectOutputStream. 

 Example 2:

Output:

Successfully read student object from the file.
Student [name=John, age=25]
Name = John
Age = 25

The only difference between FileInputStream and ObjectInputStream is :  

FileInputStreamObjectInputStream
The Java FileInputStream class, in java.io.FileInputStream, makes it possible to read the contents of a file as a stream of bytes, hence FileInputStream can be used for Serialization.ObjectInputStream in Java can be used to convert InputStream to object. This process of conversion of the input stream to an object is called deserialization.
The Java FileInputStream class obtains input bytes from a file.It can also be used to pass the objects between hosts by using a SocketStream.
It is used for reading byte-oriented data.It is mainly used to deserialize the primitive data and objects which are written by using ObjectOutputStream.
The FileInputStream class contains 9 methods.The ObjectInputStrean class contains 27 methods.
Comment