In this section, you will learn how to use the ObjectOutputStream and ObjectInputStream to write and read serialized object.
In this section, you will learn how to use the ObjectOutputStream and ObjectInputStream to write and read serialized object.In this section, you will learn how to use the ObjectOutputStream and ObjectInputStream to write and read serialized object.
The classes ObjectOutputStream and ObjectInputStream provides persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. Objects that support the java.io.Serializable or java.io.Externalizable interface can only be read from streams and write to streams.
In the given example, we have created a class student that implements Serializable interface. It is having a constructor that accepts all the student information. Now to write the object of Student class to a stream, we have called the writeObject() method of the ObjectOutputStream class and passed the serialized object to it. To read that object and display its information, we have called the readObject() method of ObjectInputStream.
Here is the code:
import java.io.*; public class ObjectsInFile { public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("C:/students.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); Student st = new Student("1", "Rose", "Rohini,Delhi"); oos.writeObject(st); oos.flush(); oos.close(); FileInputStream fis = new FileInputStream("C:/students.txt"); ObjectInputStream ois = new ObjectInputStream(fis); st = (Student) ois.readObject(); System.out.println(st.toString()); ois.close(); } } class Student implements Serializable { private String id; private String name; private String address; public Student(String id, String name, String address) { this.id = id; this.name = name; this.address = address; } public String toString() { return "Student: " + id + ", " + name + ", " + address; } }