Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - ObjectOutputStream writeObject(Object obj) method



Description

The Java ObjectOutputStream writeObject(Object obj) method writes the specified object to the ObjectOutputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are written. Default serialization for a class can be overridden using the writeObject and the readObject methods. Objects referenced by this object are written transitively so that a complete equivalent graph of objects can be reconstructed by an ObjectInputStream.

writeObject(Object obj)

  • Serializes a Java object to an output stream.

  • The object must implement the Serializable interface.

  • Supports nested objects, arrays, collections, and class metadata.

  • Paired with ObjectInputStream.readObject() to deserialize.

Declaration

Following is the declaration for java.io.ObjectOutputStream.writeObject(Object obj) method.

public void writeObject(Object obj)

Parameters

  • obj − The object to be written.

Return Value

This method does not return a value.

Exception

  • InvalidClassException − Something is wrong with a class used by serialization.

  • NotSerializableException − Some object to be serialized does not implement the java.io.Serializable interface.

  • IOException − If I/O errors occur while writing to the underlying stream.

Example - Usage of ObjectOutputStream writeObject(Object obj) method

The following example shows the usage of ObjectOutputStream writeObject(Object obj) method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello world!";
      int i = 897648764;
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeObject(s);
         oout.writeObject(i);

         // close the stream
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print what we wrote before
         System.out.println("" + (String) ois.readObject());
         System.out.println("" + ois.readObject());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Hello world!
897648764

Example - Serialize and deserialize a simple object

The following example shows the usage of ObjectOutputStream writeObject(Object obj) method. We're writing a User object to a file, then read it back.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

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

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String filename = "user1.ser";

      // Write object
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         User user = new User("alice", 25);
         oos.writeObject(user);
         System.out.println("User object serialized.");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Read object
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         User user = (User) ois.readObject();
         System.out.println("Deserialized user: " + user.name + ", age " + user.age);
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }

   static class User implements Serializable {
      String name;
      int age;
      User(String name, int age) {
         this.name = name;
         this.age = age;
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

User object serialized.
Deserialized user: alice, age 25

Example - Serialize a list of objects using writeObject()

The following example shows the usage of ObjectOutputStream writeObject(Object obj) method. We're serialize a List<Product> to a file and restore it.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String filename = "products.ser";

      List<Product> products = Arrays.asList(
         new Product("Laptop", 1500),
         new Product("Phone", 800)
      );

      // Serialize list of products
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         oos.writeObject(products);
         System.out.println("Product list serialized.");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Deserialize list
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         @SuppressWarnings("unchecked")
         List<Product> restored = (List<Product>) ois.readObject();
         System.out.println("Deserialized products:");
         for (Product p : restored) {
            System.out.println(" - " + p.name + ": $" + p.price);
         }
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }

   static class Product implements Serializable {
      String name;
      double price;
      Product(String name, double price) {
         this.name = name;
         this.price = price;
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Product list serialized.
Deserialized products:
 - Laptop: $1500.0
 - Phone: $800.0
java_io_objectoutputstream.htm
Advertisements