ObjectOutputStream

In this chapter you will learn:

  1. How to use ObjectOutputStream
  2. How to save Java objects to a file with ObjectOutputStream

Use ObjectOutputStream

The ObjectOutput interface extends the DataOutput interface and supports object serialization.

The ObjectOutputStream class extends the OutputStream class and implements the ObjectOutput interface. It is responsible for writing objects to a stream.

A constructor of this class is

ObjectOutputStream(OutputStream outStream) throws IOException

outStream is the output stream to which serialized objects will be written.

Persist Java objects

In the following we use ObjectOutputStream to persist Java objects, one string object and one date object, to a file.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
//from  jav  a2  s  .  co  m
public class Main {
  public static void main(String args[]) throws IOException {
    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeInt(12345);
    oos.writeObject("Today");
    oos.writeObject(new Date());

    oos.close();

  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use Java BufferedOutputStream to write faster