How to write an Object to file in Java

1. Overview

In this example, we will use ObjectOutputStream class to write employee object to file.
  • To write or send the object to the external world the object must implement interface type.
  • It means this object's class must be a subclass of a interface, else write() method throws
  • The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
We can also write String, Arrays, Integer, and date to file using ObjectOutputStream class because these classes internally implement a interface.

2. Write an Object to File Example

Let's first create Employee class and which implements a interface.
class Employee implements Serializable {
 private static final long serialVersionUID = 1L;
 private int id;
 private String name;

 public int getId() {
  return id;

 public void setId(int id) { = id;

 public String getName() {
  return name;

 public void setName(String name) { = name;
Let's create an employees.txt file under some directory. Write code to write employee object to file employees.txt.
 * This Java program demonstrates how to write object in file.
 * @author

public class ObjectOutputStreamExample {

 public static void main(String[] args) {
  final Employee employee = new Employee();
  try (final FileOutputStream fout = new FileOutputStream("employees.txt");
    final ObjectOutputStream out = new ObjectOutputStream(fout)) {
  } catch (IOException e) {

3. Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course