ObjectInputStream defaultReadObject() method in Java with examples
Last Updated :
05 Jun, 2020
The defaultReadObject() method of the ObjectInputStream class in Java is used to read the non-static and non-transient fields of the current class from this stream.
Syntax:
public void defaultReadObject()
Parameters: This method does not accept any parameter.
Return Value: This method returns the value that has been read.
Errors and Exceptions: The function throws three exceptions which is described below:
- ClassNotFoundException: The exception is thrown if the class of a serialized object could not be found.
- IOException: The exception is thrown if an I/O error has occurred.
- NotActiveException: The exception is thrown if the stream is not currently reading objects.
Below program illustrate the above method:
Program 1:
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
FileOutputStream out
= new FileOutputStream( "Shubham.txt" );
ObjectOutputStream out1
= new ObjectOutputStream(out);
out1.writeObject( new solve());
out1.flush();
ObjectInputStream example
= new ObjectInputStream(
new FileInputStream( "Shubham.txt" ));
solve ans = (solve)example.readObject();
System.out.println(ans.str);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
static class solve implements Serializable {
String str = "Geeksforgeeks" ;
private void readObject(ObjectInputStream res)
throws IOException,
ClassNotFoundException
{
res.defaultReadObject();
}
}
}
|
Output:
Program 2:
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
FileOutputStream out
= new FileOutputStream( "Shubham.txt" );
ObjectOutputStream out1
= new ObjectOutputStream(out);
out1.writeObject( new solve());
out1.flush();
ObjectInputStream example
= new ObjectInputStream(
new FileInputStream( "Shubham.txt" ));
solve ans = (solve)example.readObject();
System.out.println(ans.in);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
static class solve implements Serializable {
Integer in = new Integer( 112414 );
private void readObject(ObjectInputStream res)
throws IOException,
ClassNotFoundException
{
res.defaultReadObject();
}
}
}
|
Output:
Reference:
https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#defaultReadObject()
Share your thoughts in the comments
Please Login to comment...