Sometimes you want to take a Java object and persist it, perhaps to a file to be later recreated as an object again. The Java ObjectOutputStream class allows you to do just that. It takes a Java object and flattens it out into a stream of bytes. You can then save it to a file, send it across a network, or do anything you want with it.
In this video tutorial we show you how to use the java.io.ObjectOutputStream class. We will use the writeObject(Object o) method to write the bytes to a file on the local operating system using the java.io.FileOutputStream class. We will then take that file and recreate the Java object from the stream of bytes.
Here is how to construct the ObjectOutputStream:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“full/path/to/file/name”));
Once you have this object, you simply need to call the writeObject method:
Person p = new Person();
oos.writeObject(p);
To read from the created file, you use the java.io.ObjectInputStream class:
ObjectInputStream fis = new ObjectInputStream(new FileInputStream(“full/path/to/file/name”));
Person p = (Person)fis.readObject();
Please Share This Knowledge With Others!