Java.io.ObjectOutputStream.defaultWriteObject() Method

Advertisements


Description

The java.io.ObjectOutputStream.defaultWriteObject() method writes the non-static and non-transient fields of the current class to this stream. This may only be called from the writeObject method of the class being serialized. It will throw the NotActiveException if it is called otherwise.

Declaration

Following is the declaration for java.io.ObjectOutputStream.defaultWriteObject() method

public void defaultWriteObject()

Parameters

  • NA

Return Value

This method does not return a value

Exception

  • IOException -- if I/O errors occur while writing to the underlying OutputStream

Example

The following example shows the usage of java.io.ObjectOutputStream.defaultWriteObject() method.

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {

   public static void main(String[] args) {

      int i = 319874;
      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.writeInt(i);
         oout.writeInt(1653984);
         oout.flush();

         // 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 an int
         System.out.println("" + ois.readInt());

         // read and print an int
         System.out.println("" + ois.readInt());

      } catch (Exception ex) {
         ex.printStackTrace();
      }

   }

   static class Example implements Serializable {

      String s = "Hello World!";

      private void writeObject(ObjectOutputStream out)
              throws IOException, ClassNotFoundException {
         out.defaultWriteObject();

      }
   }
}

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

319874
1653984



Advertisements
Advertisements