Java.io.ObjectOutputStream Class in Java | Set 1
Last Updated :
12 Sep, 2023
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();
}
}
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
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read