Java IO ObjectInputStream and ObjectOutputStream Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 28 July 2019   |   Print Email
This Java File IO tutorial helps you understand and use the object streams classes ObjectInputStream and ObjectOutputStream in the Java File I/O API.
You use object streams to read and write Java objects in binary format. ObjectInputStream and ObjectOutputStream are the main object stream classes provided by the Java File I/O API.
The ObjectOutputStream class implements the ObjectOutput interface that defines a method for writing an object to an output stream:
- writeObject(Object): writes an object to the underlying storage or stream. This method throws IOException if an I/O error occurs.
The process of writing an object to an output stream is called Serialization.
The ObjectOutput interface extends from the DataOutput interface, which means an ObjectOutputStream inherits all behaviors of writing primitive types and Strings like a DataOutputStream.
Likewise, the ObjectInputStream class implements the ObjectInput interface that defines a method for reading an object from an input stream:
- readObject(): reads and returns an object. This method throws ClassNotFoundException if the class of the serialized object cannot be found, and throws IOException if an I/O error occurs.
The process of reconstructing an object from an input stream is called deserialization.
The ObjectInput interface extends from the DataInput interface, which means an ObjectInputStream also has behaviors of reading primitive types and Strings like a DataInputStream.
The following class diagram depicts the API hierarchy of object stream classes and interfaces:
Which kinds of object are eligible for serialization?
Note that only objects of classes that implement the java.io.Serializable interface can be written to and read from an output/input stream. Serializable is a marker interface, which doesn’t define any methods. Only objects that are marked ‘serializable’ can be used with ObjectOutputStream and ObjectInputStream.
Most classes in Java (including Date and primitive wrappers Integer, Double, Long, etc) implement the Serializable interface. You have to implement this interface for your custom classes only, such as the Student class you see in the previous email about data streams.
If you attempt to write an object of a non-serializable class, you will get a java.io.NotSerializableException.
Now, let’s see some code examples.
Given the Student class looks like this:
import java.util.Date; import java.io.Serializable; /** * Student.java * This class represents a Student * * @author www.codejava.net */ public class Student implements Serializable { private String name; private Date birthday; private boolean gender; // true is male, false is female private int age; private float grade; public Student() { } public Student(String name, Date birthday, boolean gender, int age, float grade) { this.name = name; this.birthday = birthday; this.gender = gender; this.age = age; this.grade = grade; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public boolean getGender() { return this.gender; } public void setGender(boolean gender) { this.gender = gender; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public float getGrade() { return this.grade; } public void setGrade(float grade) { this.grade = grade; } }
As you can see, this class implements the Serializable interface and has 5 member variables of various data types. We will write two programs for writing and reading objects of this class using the ObjectInputStream and ObjectOutputStream classes.
Writing Objects to a File by using the ObjectOutputStream class:
The following StudentRecordWriter program uses the ObjectOutputStream class to write a list of Students object to a file on disk:
import java.util.*; import java.text.*; import java.io.*; /** * StudentRecordWriter.java * This program illustrates how to use the ObjectOutputStream class for writing * a list of objects to a file. * * @author www.codejava.net */ public class StudentRecordWriter { public static void main(String[] args) { if (args.length < 1) { System.out.println("Please provide output file"); System.exit(0); } String outputFile = args[0]; DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); try ( ObjectOutputStream objectOutput = new ObjectOutputStream(new FileOutputStream(outputFile)); ) { List<Student> listStudent = new ArrayList<>(); listStudent.add( new Student("Alice", dateFormat.parse("02-15-1993"), false, 23, 80.5f)); listStudent.add( new Student("Brian", dateFormat.parse("10-03-1994"), true, 22, 95.0f)); listStudent.add( new Student("Carol", dateFormat.parse("08-22-1995"), false, 21, 79.8f)); for (Student student : listStudent) { objectOutput.writeObject(student); } } catch (IOException | ParseException ex) { ex.printStackTrace(); } } }
Run this program via command line:
java StudentRecordWriter Student.db
You will see a file named student.db created, but it is in binary format, which means you cannot view its content using a text editor.
Reading Objects from a File by using the ObjectInputStream class:
The following StudentRecordReader program uses the ObjectInputStream class to read objects from a file on disk:
import java.text.*; import java.io.*; /** * StudentRecordReader.java * This program illustrates how to use the ObjectInputStream class for reading * objects from a file. * * @author www.codejava.net */ public class StudentRecordReader { public static void main(String[] args) { if (args.length < 1) { System.out.println("Please provide input file"); System.exit(0); } String inputFile = args[0]; DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); try ( ObjectInputStream objectInput = new ObjectInputStream(new FileInputStream(inputFile)); ){ while (true) { Student student = (Student) objectInput.readObject(); System.out.print(student.getName() + "\t"); System.out.print(dateFormat.format(student.getBirthday()) + "\t"); System.out.print(student.getGender() + "\t"); System.out.print(student.getAge() + "\t"); System.out.println(student.getGrade()); } } catch (EOFException eof) { System.out.println("Reached end of file"); } catch (IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } }
Run this program via command line:
java StudentRecordReader Student.db
Output:
Alice 02-15-1993 false 23 80.5 Brian 10-03-1994 true 22 95.0 Carol 08-22-1995 false 21 79.8 Reached end of file
API References:
Related Java File IO Tutorial:
- Java IO DataInputStream and DataOutputStream Examples
- Java IO FileInputStream and FileOutputStream Examples
- Java IO FileReader and FileWriter Examples
Other Java File IO Tutorials:
- How to Read and Write Text File in Java
- How to Read and Write Binary Files in Java
- How to list files and directories in a directory in Java
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to compress files in ZIP format in Java
- How to extract ZIP file in Java
- Java Scanner Tutorial and Code Examples
Comments
This is a good article to understand the binary files in java.