ObjectOutputStream in Java

ObjectOutputStream enables us to write Java objects to an OutputStream. You wrap an OutputStream in a ObjectOutputStream and then you can write objects to it.

ObjectInputStream is used to read the objects back.

ObjectOutputStream and ObjectInputStream is used in Serialization. Please read Serialization in Java for more details.

Constructor

ObjectOutputStream in Java

package com.java.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamExample {

    public static void main(String[] args) {

        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            Employee employee = new Employee("Gyan", 1);
            fos = new FileOutputStream("/Test/TestFolder/test-file5.txt");
            oos = new ObjectOutputStream(fos);
            //Writing Object to File
            oos.writeObject(employee);
            oos.flush();
            System.out.println("Data Employee Object to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // Closing the streams
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (oos != null)
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}

class Employee implements Serializable {

    private static final long serialVersionUID = 1 L;
    public Employee(String name, Integer id) {
        this.name = name;
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    private String name;
    private Integer id;

}
Data Employee Object to File

File

We will see garbled characters.

Screen Shot 2020-03-31 at 7.29.43 PM

Leave a Reply

Your email address will not be published. Required fields are marked *