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:
Hierarchy of classes to deal with Input streamsExample 1:
Java
// Java program to demonstrate Use of FileInputStream class
// Importing the desired class
import java.io.FileInputStream;
// Importing input output class from java.io package
import java.io.IOException;
// Main class
class FileInputStreamGFG {
// Method 1
// To read from the file
private void readFile() throws IOException
{
// Creating an object of FileInputStream
FileInputStream fileInputStream = null;
// Try block to check for exceptions
try {
// Now, creating a FileInputStream by
// opening a connection to an actual file
// The file named by the path name in the
// file system
// Here customly we have taken
// gfg.txt contains fileInputStream
= new FileInputStream("gfg.txt");
// data - "Java was called
// Oak at the beginning."
int i;
// Reads a byte of data from this input stream
// using read() method
// Till condition holds true
while ((i = fileInputStream.read()) != -1) {
// Print the stream
System.out.print((char)i);
}
}
// If there is any exception encountered
// then execute this block
finally {
// Stream is not there in file
if (fileInputStream != null) {
// Then close this file input stream and
// releases any system resources associated
// with the stream using close() method
fileInputStream.close();
}
}
}
// Method 2
// Main driver method
public static void main(String[] args)
throws IOException
{
// Constructor of this class
FileInputStreamGFG fileInputStreamGfg
= new FileInputStreamGFG();
// Calling the readFile() method
// in the main() method
fileInputStreamGfg.readFile();
}
}
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:
Java
// Java program to demonstrate Use of ObjectInputStream
// class
// Importing required input output classes
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
// Before serialization and de-serialization of objects the
// class of the object must implement java.io.Serializable
// Class 1
// Helper class implementing Serializable interface
class Student implements Serializable {
// Private class member variables
private static final long serialVersionUID
= -1438960132000208485L;
private String name;
private int age;
// Constructor of this class
public Student(String name, int age)
{
// super keyword refers to parent class
super();
// this keyword refers to current object instance
this.name = name;
this.age = age;
}
// Getters and Setter for class
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
// Override toString method
@Override public String toString()
{
// Simply return the name and age
return "Student [name=" + name + ", age=" + age
+ "]";
}
}
// Class 2
// Main class
public class ObjectInputStreamDemo {
// Main driver method
public static void main(String[] args)
throws FileNotFoundException, IOException,
ClassNotFoundException
{
// Creating an object of above class
// in the main() method
ObjectInputStreamDemo objectInputStreamDemo
= new ObjectInputStreamDemo();
// Readfile function call
objectInputStreamDemo.readStudentObject();
}
// Member method of main class
private void readStudentObject()
throws IOException, FileNotFoundException,
ClassNotFoundException
{
// Initially null is set to both streams
// read and write streams
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
// Try block to check for exceptions
try {
// Input stream directory
fileInputStream
= new FileInputStream("student.txt");
// Input stream object
objectInputStream
= new ObjectInputStream(fileInputStream);
// Creating an object of above class to
// read an object from the ObjectInputStream
Student student
= (Student)objectInputStream.readObject();
// Display message when input stream is
// completely read
System.out.println(
"Successfully read student object from the file.");
// Print an display commands
System.out.println(student);
System.out.println("Name = "
+ student.getName());
System.out.println("Age = "
+ student.getAge());
}
// When an exception is encountered execute the
// block
finally {
// If there is nothing to be read
if (objectInputStream != null) {
// Then close a ObjectInputStream will
// the InputStream instance from which
// the ObjectInputStream is reading
// isong the close() method
objectInputStream.close();
}
}
}
}
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 : Â
FileInputStream | ObjectInputStream |
---|
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. |
Similar Reads
Difference Between ObjectInputStream and ObjectOutputStream in Java In a software project, in many instances, there are necessities to transfer the data, and it can be handled by using ObjectOutputStream and ObjectInputStream from Java IO packages. Usually, the data is written in binary format and hence we cannot view the contents. Serialization is the process of wr
8 min read
Difference Between FileInputStream and FileReader in Java Let us first do discuss them in order to get the understanding alongside an example to interpret the differences. Here first we will be discussing out FileReader class. So starting of with FileReader class in java is used to read data from the file. It returns data in byte format like FileInputStrea
4 min read
Difference Between ZipFile and ZipInputStream in Java Zip files are basically an archive file that is used to compress all the files in one place. Doing this reduces memory space occupied and makes transport of files bundle easy. ZipInputStream which are used to read the file entries in zip files present in the zip. In Java, there are two classes namel
5 min read
Difference between Program and File 1. Program : Program, as name suggest, are simple executable files that contain set or collection of instructions used by computer to execute or complete particular tasks as well as produce results you want. 2. File : File, as name suggests, is basic concept in computer that is designed to store dat
2 min read
Difference Between Streams and Collections in Java Collection is an in-memory data structure, which holds all the values that the data structure currently has. Every element in the Collection has to be computed before we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Colle
3 min read
Difference between Stream.of() and Arrays.stream() method in Java Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example:Â Java // Java program to demo
5 min read
Difference Between BufferedReader and FileReader in Java BufferedReader and FileReader both classes are used to read data from a given character stream. Both of them have some pros and some cons. In this article, we will discuss the differences between them. Though the most important difference is in the way they work, but we will discuss the other detail
10 min read
Difference Between Serializable and Externalizable in Java Serialization The process of writing the state of an object to a file is called serialization, but strictly speaking, it is the process of converting an object from java supported form into a file-supported form or network-supported form by using fileOutputStream and objectOutputStream classes we can implement se
6 min read
FileInputStream available() Method in Java with Examples The available() method of FileInputStream class is used to return the estimated number of remaining bytes that can be read from the input stream without blocking. This method returns the number of bytes remaining to read from the file. When a file is completely read, this function returns zero. Synt
3 min read
Difference Between Object And Class Class is a detailed description, the definition, and the template of what an object will be. But it is not the object itself. Also, what we call, a class is the building block that leads to Object-Oriented Programming. It is a user-defined data type, that holds its own data members and member functi
6 min read