Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.OutputStream class in Java
Next article icon

Java.io.ObjectOutputStream Class in Java | Set 1

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

Java




//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();
    }
}
 
 

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

Java




//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();
    }
}
 
 

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

Java




//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();
    }
}
 
 
  • 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 

Java




//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();
  
        }
    }
  
     }
 
 

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

Java




//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();
    }
}
 
 
  • 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

Java




//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();
    }
}
 
 

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

Java




//Java program demonstrating ObjectOutputStream
//illustrating 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();
  
    }
}
 
 

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

Java




//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();
    }
}
 
 

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 

Java




//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();
    }
}
 
 

Output : 

GeeksforGeeks

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

 



Next Article
Java.io.OutputStream class in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java.io.ObjectInputStream Class in Java | Set 1
    ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
    9 min read
  • Java.io.ObjectInputStream Class in Java | Set 2
    Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
    6 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
  • Java.io.Printstream Class in Java | Set 1
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the c
    5 min read
  • Java.io.Printstream Class in Java | Set 2
    Java.io.Printstream Class in Java | Set 1More Methods: PrintStream printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this output stream using the specified format string and arguments. Syntax :public PrintStream printf(Locale l, String format, Obje
    6 min read
  • Java.io.PipedInputStream class in Java
    Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
    5 min read
  • Java.io.PushbackInputStream class in Java
    Pushback is used on an input stream to allow a byte to be read and then returned (i.e, "pushed back") to the stream. The PushbackInputStream class implements this idea. It provides a mechanism "peek" at what is coming from an input stream without disrupting it. It extends FilterInputStream.Fields: p
    7 min read
  • Java.io.PrintWriter class in Java | Set 1
    Java PrintWriter class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. Unlike the PrintStream class, if au
    5 min read
  • Java.io.LineNumberInputStream Class in Java
    java.io.LineNumberInputStream class is simply an extension of input stream providing a extra facility to keep the record of current line number. Line is a sequence of bytes ending with : '\r' i.e. a carriage return character or a newline character : '\n', or a linefeed character following the carria
    11 min read
  • Java.io.ObjectStreamClass in Java
    This class is serialization's descriptor for classes. It contains the name and serialVersionUID of the class. The ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method. It extends class Object and implement serialisable. Fields: static ObjectStrea
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences