Java.io.ObjectOutputStream Class in Java | Set 1

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream.

  • Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object’s fields and arrays, and the closure of any other objects referenced from the initial objects.
  • The Java ObjectOutputStream is often used together with a Java ObjectInputStream. The ObjectOutputStream is used to write the Java objects, and the ObjectInputStream is used to read the objects again.

Constructors :

  • protected ObjectOutputStream() : Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.
  • ObjectOutputStream(OutputStream out) : Creates an ObjectOutputStream that writes to the specified OutputStream.

Methods:

  • protected void annotateClass(Class cl) : Subclasses may implement this method to allow class data to be stored in the stream. By default this method does nothing. The corresponding method in ObjectInputStream is resolveClass. This method is called exactly once for each unique class in the stream. The class name and signature will have already been written to the stream. This method may make free use of the ObjectOutputStream to save any representation of the class it deems suitable (for example, the bytes of the class file). The resolveClass method in the corresponding subclass of ObjectInputStream must read and use any data or objects written by annotateClass.
    Syntax :protected void annotateClass(Class cl)
                          throws IOException
    Parameters:
    cl - the class to annotate custom data for
    Throws:
    IOException 
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream methods
    //illustrating annotateClass(Class<?> cl) method
      
    import java.io.*;
    class ObjectOutputStreamDemo extends ObjectOutputStream
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
          
        public static void main(String[] args) throws IOException,
        ClassNotFoundException 
        {
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);
            Character c = 'A';
              
            //illustrating annotateClass(Class<?> cl) method
            oot.annotateClass(Character.class);
              
            //Write the specified object to the ObjectOutputStream
            oot.writeObject(c);
              
            //flushing the stream
            oot.flush();
              
            //closing the stream
            oot.close();
              
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
            System.out.print(oit.readObject());
            oit.close();
        }
    }

    chevron_right

    
    

    Output :

    A
  • protected void annotateProxyClass(Class cl) : Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes.This method is called exactly once for each unique proxy class descriptor in the stream. The default implementation of this method in ObjectOutputStream does nothing.

    The corresponding method in ObjectInputStream is resolveProxyClass. For a given subclass of ObjectOutputStream that overrides this method, the resolveProxyClass method in the corresponding subclass of ObjectInputStream must read any data or objects written by annotateProxyClass.



    Syntax :protected void annotateProxyClass(Class cl)
                               throws IOException
    Parameters:
    cl - the proxy class to annotate custom data for
    Throws:
    IOException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream 
    //illustrating annotateProxyClass(Class<?> cl) method
    import java.io.*;
      
    class ObjectOutputStreamDemo extends ObjectOutputStream
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
          
        public static void main(String[] args) throws IOException, 
        ClassNotFoundException
        {
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);
              
            Character c = 'A';
              
            //illustrating annotateProxyClass(Class<?> cl) method
            oot.annotateProxyClass(Character.class);
              
            //Write the specified object to the ObjectOutputStream
            oot.writeObject(c);
              
            //flushing
            oot.flush();
              
            //closing the stream
            oot.close();
              
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
            System.out.print(oit.readObject());
            oit.close();
        }
    }

    chevron_right

    
    

    Output :

    A
  • void close() : Closes the stream.This method must be called to release any resources associated with the stream.
    Syntax :public void close()
               throws IOException
    Throws:
    IOException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream 
    //illustrating close() method
      
    import java.io.*;
    class ObjectOutputStreamDemo
    {
        public static void main(String[] args) throws IOException
        {
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStream oot = new ObjectOutputStream(fout);
            oot.write(3);
              
            //illustrating close()
            oot.close();
              
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
            System.out.println(oit.read());
            oit.close();
        }
    }

    chevron_right

    
    

    Output :

    3
  • void defaultWriteObject() : Write 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.
    Syntax :public void defaultWriteObject()
                            throws IOException
    Throws:
    IOException 
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream
    //illustrating defaultWriteObject() method
      
    import java.io.*;
    class ObjectOutputStreamDemo
    {
        public static void main(String[] arg) throws IOException,
                ClassNotFoundException
        {
                Character a = 'A';
                FileOutputStream fout = new FileOutputStream("file.txt");
                ObjectOutputStream oot = new ObjectOutputStream(fout);
                oot.writeChar(a);
                oot.flush();
                  
                // close the stream
                oot.close();
                  
                FileInputStream fin = new FileInputStream("file.txt");
                ObjectInputStream oit = new ObjectInputStream(fin);
                  
                // reading the character
                System.out.println(oit.readChar());
        }
    }
        class demo implements Serializable 
        {
            String s = "GeeksfoGeeks";
            private void writeObject(ObjectOutputStream out)
                    throws IOException, ClassNotFoundException
            {
                //demonstrating defaultWriteObject()
                out.defaultWriteObject();
      
            }
        }
      
         }

    chevron_right

    
    

    Output :

    A
  • protected void drain() : Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to the underlying stream.
    Syntax :protected void drain()
                  throws IOException
    Throws:
    IOException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream methods
    //illustrating drain() method
    import java.io.*;
    class ObjectOutputStreamDemo extends ObjectOutputStream
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
        public static void main(String[] arg) throws IOException,
                ClassNotFoundException
        {
                FileOutputStream fout = new FileOutputStream("file.txt");
                ObjectOutputStream oot = new ObjectOutputStream(fout);
                ObjectOutputStreamDemo obj = new ObjectOutputStreamDemo(oot);
                  
                //illustrating drain()
                obj.drain();
                  
                //closing the underlying stream
                oot.close();
                fout.close();
        }
    }

    chevron_right

    
    

  • protected boolean enableReplaceObject(boolean enable) : Enable the stream to do replacement of objects in the stream.When enabled, the replaceObject method is called for every object being serialized.
    If enable is true, and there is a security manager installed, this method first calls the security manager’s checkPermission method with a SerializablePermission(“enableSubstitution”) permission to ensure it’s ok to enable the stream to do replacement of objects in the stream.

    Syntax :protected boolean enableReplaceObject(boolean enable)
                                   throws SecurityException
    Parameters:
    enable - boolean parameter to enable replacement of objects
    Returns:
    the previous setting before this method was invoked
    Throws:
    SecurityException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream
    //illustrating enableReplaceObject method
    import java.io.*;
    class ObjectOutputStreamDemo extends ObjectOutputStream 
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
      
        public static void main(String[] args) throws IOException, 
            ClassNotFoundException
            {
                FileOutputStream fout = new FileOutputStream("file.txt");
                ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);
                Character c = 'A';
                  
                //illustrating enableReplaceObject method
                System.out.println(oot.enableReplaceObject(true));
                  
                //Write the specified object to the ObjectOutputStream
                oot.writeObject(c);
                  
                //flushing
                oot.flush();
                  
                //closing the stream
                oot.close();
                  
                FileInputStream fin = new FileInputStream("file.txt");
                ObjectInputStream oit = new ObjectInputStream(fin);
                System.out.print(oit.readObject());
                oit.close();
        }
    }

    chevron_right

    
    

    Output :

    false
    A
  • ObjectOutputStream.PutField putFields() : Retrieve the object used to buffer persistent fields to be written to the stream.The fields will be written to the stream when writeFields method is called.
    Syntax :public ObjectOutputStream.PutField putFields()
                                          throws IOException
    Returns:
    an instance of the class Putfield that holds the serializable fields
    Throws:
    IOException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream
    //illustating PutField method
    import java.io.*;
    class ObjectOutputStreamDemo
    {
        public static void main(String[] arg) throws IOException,
                ClassNotFoundException
        {
            Character a ='A';
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStream oot = new ObjectOutputStream(fout);
            oot.writeChar(a);
            oot.flush();
              
            // close the stream
            oot.close();
              
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
              
            // reading the character
            System.out.println(oit.readChar());
        }
    }
    class demo implements Serializable
    {
        private void writeObject(ObjectOutputStream out)
                throws IOException, ClassNotFoundException
        {
            // Retrieve the object used to buffer
            // persistent fields to be written to the stream
            ObjectOutputStream.PutField fields = out.putFields();
      
        }
    }

    chevron_right

    
    

    Output :

    A
  • protected Object replaceObject(Object obj) : This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacement can be trusted. The first occurrence of each object written into the serialization stream is passed to replaceObject. Subsequent references to the object are replaced by the object returned by the original call to replaceObject. To ensure that the private state of objects is not unintentionally exposed, only trusted streams may use replaceObject.
    This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object. This method should return the object to be substituted or the original object.

    Null can be returned as the object to be substituted, but may cause NullReferenceException in classes that contain references to the original object since they may be expecting an object instead of null.



    Syntax :protected Object replaceObject(Object obj)
                            throws IOException
    Parameters:
    obj - the object to be replaced
    Returns:
    the alternate object that replaced the specified one
    Throws:
    IOException
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream
    //illustrating replaceObject method
    import java.io.*;
    class ObjectOutputStreamDemo extends ObjectOutputStream
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
      
        public static void main(String[] args) throws IOException, 
        ClassNotFoundException 
        {
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);
            String a = "forGeeks";
            String b = "Geeks";
      
            //Write the specified object to the ObjectOutputStream
            oot.writeObject(a);
              
            //flushing the stream
            oot.flush();
      
            oot.enableReplaceObject(true);
              
            //illustrating replaceObject
            System.out.print(oot.replaceObject(b));
              
            //closing the stream
            oot.close();
              
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
            System.out.print(oit.readObject());
            oit.close();
        }
    }

    chevron_right

    
    

    Output :

    GeeksforGeeks
  • void useProtocolVersion(int version) : Specify stream protocol version to use when writing the stream.This routine provides a hook to enable the current version of Serialization to write in a format that is backwards compatible to a previous version of the stream format.

    Every effort will be made to avoid introducing additional backwards incompatibilities; however, sometimes there is no other alternative.

    Syntax :public void useProtocolVersion(int version)
                            throws IOException
    Parameters:
    version - use ProtocolVersion from java.io.ObjectStreamConstants.
    Throws:
    IllegalStateException 
    IllegalArgumentException
    IOException 
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    //Java program demonstrating ObjectOutputStream
     //illustrating useProtocolVersion() method
    import java.io.*;
    class ObjectOutputStreamDemo extends ObjectOutputStream
    {
        public ObjectOutputStreamDemo(OutputStream out) throws IOException
        {
            super(out);
        }
      
        public static void main(String[] args) throws IOException, 
            ClassNotFoundException 
        {
            FileOutputStream fout = new FileOutputStream("file.txt");
            ObjectOutputStreamDemo oot = new ObjectOutputStreamDemo(fout);
            String a = "forGeeks";
            String b = "Geeks";
      
            //illustrating useProtocolVersion()
            oot.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);
      
            //Write the specified object to the ObjectOutputStream
            oot.writeObject(b);
            oot.writeObject(a);
      
            //flushing the stream
            oot.flush();
      
            oot.close();
            FileInputStream fin = new FileInputStream("file.txt");
            ObjectInputStream oit = new ObjectInputStream(fin);
            System.out.print(oit.readObject());
            System.out.print(oit.readObject());
            oit.close();
        }
    }

    chevron_right

    
    

    Output :

    GeeksforGeeks

Next Article : Java.io.ObjectOutputStream Class in Java | Set 2

This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.