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 ObjectInputStream Class :

  • defaultReadObject() : java.io.ObjectInputStream.defaultReadObject() reads the non-static field of the current class from the Input Stream. We use readObject() method of the serialized class to call this method.
    Syntax :

    public void defaultReadObject()
    Parameters : 
    -----------
    Return : 
    void
    Exception :
    -> IOException : in case of any IO error occurs.
    -> ClassNotFoundException : if the class of Object(being serialized) is not found
    -> NotActiveException : if the Stream is not reading.
    
  • readObject() : java.io.ObjectInputStream.readObject() reads an object from the serialized class. This method is used to call the defaultReadObject. If the class is deserialized by defaut, then it can be overridden using the readObject and writeObject methods.
    Syntax :

    public void defaultReadObject()
    Parameters : 
    public final Object readObject()
    Return : 
    void
    Exception :
    -> IOException : in case of any IO error occurs.
    -> ClassNotFoundException : if the class of Object(being serialized) is not found
    -> OptionalDataException : if instead of object, primitive data is found.
    -> InvalidClassException : is there is something wrong with serialized class
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of
    // readObject() and defaultReadObject() 
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream 
                = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeObject(new Geek());
            geek_outStream.flush();
      
              
      
            // Use of readObject() :
            Geek a = (Geek) Geek_inStream.readObject();
      
            // Using both readObject and defaultReadObject();
            System.out.println("Using defaultReadObject by readObject : "+ a.s);
      
        }
          
        static class Geek implements Serializable
        {
      
            String s = "GeeksForGeeks";
            private void readObject(ObjectInputStream test)throws 
                                        IOException, ClassNotFoundException
            {
                // Use of defaultReadObject() :
                test.defaultReadObject();
            }
        }
    }

    chevron_right

    
    

    output :

    Using defaultReadObject by readObject : GeeksForGeeks
  • available() : java.io.ObjectInputStream.available() tells the no. of bytes of that can be read without being blocked
    Syntax :



    public int available()
    Parameters : 
    -----------
    Return : 
    no. of bytes of that can be read without being blocked
    Exception :
    -> IOException : in case of any IO error occurs.
    
  • close() : java.io.ObjectInputStream.close() closes the Input Stream and releases all the resources allocated to the Stream
    Syntax :

    public void close()
    Parameters : 
    -----------
    Return : 
    void
    Exception :
    -> IOException : in case of any IO error occurs.
    
  • readShort() : java.io.ObjectInputStream.readShort()reads 16 bit short.
    Syntax :

    public short readShort()
    Parameters : 
    public final Object readObject()
    Return : 
    reads 16 bit short.
    Exception :
    -> IOException : in case of any IO error occurs.
    -> EOFException : if End of stream is reached
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of
    // available(), readShort(),close()
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream 
                        = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeShort(3050);
            geek_outStream.writeUTF("gEEKSArehERE");
      
            geek_outStream.flush();
      
            // Use of available() method :
            System.out.println("Use of available() : " + Geek_inStream.available());
      
            // Use of readShort() method :
            System.out.println("Use of readShort() : " + Geek_inStream.readShort());
      
      
      
            // Use of close() method : to release the resources assigned to Geek_inStream
            System.out.println("Closing the stream");
            Geek_inStream.close();
      
        }
    }

    chevron_right

    
    

    Output :

    Use of available() : 16
    Use of readShort() : 3050
    Closing the stream
  • readUTF() : java.io.ObjectInputStream.readUTF()reads String in modified UTF-8 (Unicode Transformation Format) format. UTF -8 means it uses 8-bit blocks to represent a character.
    Syntax :

    public String readUTF()
    Parameters : 
    public final Object readObject()
    Return : 
    reads String in modified UTF-8 (Unicode Transformation Format) format
    Exception :
    -> IOException : in case of any IO error occurs.
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of readUTF()
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream 
                = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeUTF("gEEKSArehERE");
            geek_outStream.flush();
      
              
              
            // Use of readUTF() method :
            System.out.println("Use of readUTF() : " + Geek_inStream.readUTF());
        }
    }

    chevron_right

    
    

    Output :

    Use of readUTF() : gEEKSArehERE
  • skipBytes(int maxlen) : java.io.ObjectInputStream.skipBytes(int maxlen)skips ‘maxlen’ no. of bytes while reading.
    Syntax :

    public int skipBytes(int maxlen)
    Parameters : 
    maxlen : max. no. of bytes to be skipped
    Return : 
    no. of bytes to be skipped
    Exception :
    -> IOException : in case of any IO error occurs.
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of skipBytes()
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream 
                        = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeUTF("gEEKSArehERE");
            geek_outStream.flush();
      
              
              
            // Use of skipBytes() : 
            Geek_inStream.skipBytes(7);
              
            for (int i = 2; i < Geek_inStream.available(); i++) 
            {
                System.out.print((char) Geek_inStream.readByte());
            }
        }
    }

    chevron_right

    
    

    Output :

    Are
  • readFully(byte[] destination) : java.io.ObjectInputStream.readFully(byte[] destination)reads all the bytes from source to the destination array.
    Syntax :



    public void readFully(byte[] destination)
    Parameters : 
    destination : the buffer in which the data is to be read
    Return : 
    returns the 32 bit float read
    Exception :
    -> IOException : in case of any IO error occurs.
    -> EOFException : if End of stream is reached
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of readFully()
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream
                            = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeUTF("gEEKSArehERE");
            geek_outStream.flush();
      
              
              
            // Use of readFully() : 
            byte[] destination = new byte[14];
            Geek_inStream.readFully(destination);
            String str = new String(destination);
            System.out.println("Use of readFully(destination, offset, maxlen) : "+str);
        }
    }

    chevron_right

    
    

    Output :

    Use of readFully(destination, offset, maxlen) : gEEKSArehERE
  • readFully(byte[] destination, int offset, int maxlen) : java.io.ObjectInputStream.readFully(byte[] destination, int offset, int maxlen)reads some the bytes (starting from offset to maxlen position) from source to the destination array .
    Syntax :

    public void readFully(byte[] destination, int offset, int maxlen)
    Parameters : 
    destination : the buffer in which the data is to be read
    offset : starting position of the buffer
    maxlen : max no. of bytes to be read
    Return : 
    void
    Exception :
    -> IOException : in case of any IO error occurs.
    -> EOFException : if End of stream is reached
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program explaining the working of 
    // readFully(byte[] destination, int offset, int maxlen)
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException, ClassNotFoundException
        {
            // create a new file with an ObjectOutputStream and ObjectInputStream
            FileOutputStream geek_out = new FileOutputStream("GEEKS.txt");
            ObjectOutputStream geek_outStream = new ObjectOutputStream(geek_out);
      
            ObjectInputStream Geek_inStream 
                        = new ObjectInputStream(new FileInputStream("GEEKS.txt"));
      
            // These are ObjectOutputStream methods, Don't bother about these methods
            // As they are covered in other articles you can refer them
            geek_outStream.writeUTF("gEEKSArehERE");
            geek_outStream.flush();
      
              
              
            // Use of readFully(byte[] destination, int offset, int maxlen) : 
            byte[] destination = new byte[14];
            Geek_inStream.readFully(destination, 3, 7);
            String str = new String(destination);
            System.out.println("Use of readFully(destination, offset, maxlen) : "+ str);
        }
    }

    chevron_right

    
    

    Output :

    Use of readFully(destination, offset, maxlen) : geeks
  • readFields() : java.io.ObjectInputStream.readFields() reads the constant field from the Input Stream and indicates the name.
    Syntax :

    public ObjectInputStream.GetField readFields()
    Parameters : 
    -------
    Return : 
    GetField object reading the constant fields
    Exception :
    -> IOException : in case of any IO error occurs.
    -> ClassNotFoundException : if class of serialized object is not found
    
  • resolveClass() : java.io.ObjectInputStream.resolveClass(ObjectStreamClass INS_class) loads an instance class to Specified Stream Class in place of it.
    Syntax :

    protected Class resolveClass(ObjectStreamClass desc)
    
     : means that the class object can be of any type, it is to be specified by the coder.
    Parameters : 
    INS_class : instance of the specified Stream Class
    Return : 
    Class Object equivalent to the Specified Stream Class
    Exception :
    -> IO Exception : if any IO exception occurs
    -> ClassNotFoundException : if the argumented class is not available.
    
  • registerValidation() : java.io.ObjectInputStream.registerValidation(ObjectInputValidation object, int order) registers the object to validate it.
    Syntax :

    public void registerValidation(ObjectInputValidation object, int order)
    Parameters : 
    -------
    Return : 
    object : object to be validated 
    order : Controls the order of callback. These are processed in no particular order
    Exception :
    -> NotActiveException : If IO stream is not ready to be read
    -> InvalidObjectException : if the argumented object to be validated is NULL.
    
  • resolveObject(Object o) : java.io.ObjectInputStream.resolveObject(Object o) substitutes an object to ObjectInputStream from another trusted subclass. We can’t replace object until
    enableResolveObject is called. It is called after an object has been read.
    Syntax :

    protected Object resolveObject(Object o)
    Parameters : 
    o : object we want to substitue
    Return : 
    ---------
    Exception :
    -> IOException : If IO error occurs.
    
  • enableResolveObject() : java.io.ObjectInputStream.enableResolveObject(boolean check) allows resolveObject method to substitute an object to the ObjectInputStream from another trusted class.
    enableResolveObject is called. It is called after an object has been read.
    Syntax :

    protected boolean enableResolveObject(boolean enable)
    Parameters : 
    check : "true" to allow resolveObject() method
    Return : 
    ----
    
  • readClassDescriptor() : java.io.ObjectInputStream.readClassDescriptor() reads class descriptor from the serialized stream, this method is called if descriptor is accepted by the ObjectInputStream. By default, descriptor is called by readClassDescriptor() method acc. to the format defined in Object Serialization
    Syntax :

    protected ObjectStreamClass readClassDescriptor()
    Parameters : 
    -------
    Return : 
    reads class descriptor
    
  • readObjectOverride() : java.io.ObjectInputStream.readObjectOverride() reads object from the ObjectOutputStream using protected no-argument constructor
    Syntax :

    protected Object readObjectOverride()
    Parameters : 
    -------
    Return : 
    reads object from the Stream
    
  • readStreamHeader() : java.io.ObjectInputStream.readStreamHeader() allows subclass to read and verify their header and verifying the version number
    Syntax :

    protected void readStreamHeader()
    Parameters : 
    -------
    Return : 
    void
    
  • resolveProxyClass(String[] in_list) : java.io.resolveProxyClass(String[] in_list) returns a proxy class implementing those interfaces which are named in Proxy Class Descriptor. Using this method, we can read descriptors from the dynamic proxy classes
    Syntax :

    protected Class resolveProxyClass(String[] in_list)
    Parameters : 
    in_List : interface names list, deserialized in the proxy class descriptor
    Return : 
    Proxy class for specific Interface mentioned in the list
    
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program explaining working of ObjectInputStream class methods
      
    import java.io.*;
      
    public class ObjectInputStreamDemo extends ObjectInputStream
    {
      
        public ObjectInputStreamDemo(InputStream in) throws IOException
        {
            super(in);
        }
    }
    public class NewClass
    {
        public static void main(String[] args)
        {
            String str = "Geeks";
            try
            {
                // create a new file with an ObjectOutputStream and ObjectInputStream
                FileOutputStream geek_out = new FileOutputStream("test.txt");
                ObjectOutputStream geek_in = new ObjectOutputStream(geek_out);
      
                ObjectInputStream geek_InStream 
                            = new ObjectInputStream(new FileInputStream("test.txt"));
      
      
                // These are ObjectOutputStream methods, Don't bother about these methods
                // As they are covered in other articles you can refer them
                geek_in.writeObject(new Test());
                geek_in.writeUTF(str);
                geek_in.flush();
      
                // Gvivg true to the resove Object to enable it
                geek_InStream.enableResolveObject(true);
      
                // Using resolveObject() :
                System.out.println("resoveObject() : " 
                            + geek_InStream.resolveObject(geek_InStream.readUTF()));
      
                // read the object and print the string
                Test a = (Test) geek_InStream.readObject();
      
                // String value using readFields() methods :
                System.out.println("Using readFields() : " + a.geek);
      
                // Checking th use of registerValidation
                System.out.println("Testing the valiations : : : ");
                if (Test.geek.equals("Geeks For Geeks"))
                {
                    System.out.println("\t\t\t\tWorking Perfect ");
                }
                else
                {
                    System.out.println("Something wrong with the validations : ");
                }
            }
      
            catch (Exception excpt)
            {
                System.out.println("Error");
                excpt.printStackTrace();
            }
        }
      
        static class Test implements Serializable, ObjectInputValidation
        {
            static String geek = "Geeks For Geeks";
            private String readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException
            {
      
                // use of readFields() method :
                ObjectInputStream.GetField getfield = in.readFields();
      
                // USe of registerValidation() method :
                in.registerValidation(this, 0);
      
                // Returning String "geek" to the main
                return (String) getfield.get("geek", null);
            }
      
            @Override
            public void validateObject() throws InvalidObjectException
            {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        }
    }

    chevron_right

    
    

    Output :

    Using resoveObject() : Geeks
    Using readFields() : Geeks For Geeks
    Testing the valiations : : :  
    				Working Perfect 

    This article is contributed by Mohit Gupta 🙂. 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.