Java ObjectInputStream skipBytes() Method

Object Serialization in Java is supported by the classes, ObjectInputStream and ObjectOutputStream. The Java class ObjectInputStream has a method called skipBytes(len) and it allows to skip n bytes while reading the serialized data. This method has the signature

public int skipBytes(int len) throws IOException

This method takes the number of bytes to be skipped len as the only argument and it returns the actual number of bytes skipped. When this method is invoked on an instance of ObjectInputStream it might throw an IOException. So this method should be wrapped with atry..catch statement, otherwise, Java will raise an error. For example, consider the code,

import java.io.*;
class Sample
{
  public static void main(String[] args)
  {
    try{
      int numBytes = 20;
      String content = "This content was written to test.txt";
      ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream("test.txt"));
      oout.writeUTF(content);
      System.out.println("WRITE:\n"+content.length()+" bytes written to test.txt.");
      System.out.println("Data written: '"+content+"'");
      oout.close();
      ObjectInputStream oin = new ObjectInputStream(new FileInputStream("test.txt"));
      System.out.println("\nREAD:\n"+oin.available()+" bytes are available.");
      System.out.println(oin.skipBytes(numBytes)+" bytes are skipped.");
      System.out.println("So "+oin.available()+" bytes are available.");
      byte[] a = new byte[oin.available()];
      oin.read(a,0,oin.available());
      System.out.print("Available data: '");
      for (int i=0;i<a.length;i++)
        System.out.print((char)a[i]);
      System.out.println("'");
      oin.close();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }

In the example above, the data to be serialized is assigned to the variable content. When Java serializes it, it should have 36 bytes. Remember each character is of size 1 byte? But the file will contain 38 bytes. Because Java adds a $ at the beginning of the content.

The variable numBytes is assigned to 20, which is the number of bytes to be skipped (len). The data read from the file is deserialized after invoking the method skipBytes() on the ObjectInputStream object. The above program also prints the number of bytes left as a result of skipping len bytes.

WRITE:
36 bytes written to test.txt.
Data written: 'This content was written to test.txt'

READ:
38 bytes are available.
20 bytes are skipped.
So 18 bytes are available.
Available data: 'ritten to test.txt'

Also, read: How to Rotate an Image in Java?

Leave a Reply

Your email address will not be published. Required fields are marked *