InputStream skip() Method in Java

Hello Learners, today we are going to learn about InputStream skip method in Java. The method belongs to the InputStream class which resides in java.io package. This method is used to skip and discard n number of bytes from the input stream.

The method takes one parameter of long type. It will skip the number of bytes from the input stream that is passed as the method, every time the method is called.

Here we have a text file as demo.txt and the demo file contains 28 characters in total.

demo.txt

This is a Demo File for you!

Let’s see the code that will give you the basic idea of how the skip method functions.

import java.io.FileInputStream;
import java.io.InputStream;

public class skipmethod {
  
   public static void main(String[] args) throws Exception {
     
      InputStream is = null;
      int i, j=-2;
      char ch;
      
      try {
         is = new FileInputStream("C:\\Users\\lenovo\\Documents\\demo.txt");
         
         while((i = is.read())!=-1) {
            ch = (char)i;
            System.out.println("Character Read: "+ch);
            is.skip(2);
            j += 2;
         }
      } 
      
      catch(Exception e) {
         e.printStackTrace();
      } 
      
      finally {
    	 System.out.println("total characters skipped: "+j);
         if(is!=null)
            is.close();
      }
   }
}

OUTPUT:

Character Read: T
Character Read: s
Character Read: s
Character Read: 
Character Read: m
Character Read: F
Character Read: e
Character Read: o
Character Read: y
Character Read: !
total characters skipped: 18

Explanation

  • At first, we created an object of input stream class and opened the file by providing a valid path.
  • A while loop is added to print each character of the file.
  • Inside while loop, we have called the skip method and passed 2 as an argument. Here, don’t forget that the skip method takes one long data type number as an argument and skips those many numbers of bytes from the input stream.
  • Look at the demo file. The program reads one character from the input stream i.e. ‘T’ and prints it.
  • In the next statement, skip method is called with a value 2. now it skips the next two characters which is ‘h’ and ‘i’.
  • Again the same thing happened. jvm reads ‘s’ and skips the next two characters ‘ ‘ and ‘i’. This process will repeat until we reach the end of the file as per the given condition.
  • IN each iteration we are also calculating the number of bits skipped by adding 2 in j variable every time the skip method is called.
  • At last, in the finally block we have printed the value of j which is nothing but the number of characters skipped.

Also read: Differences between HashSet and TreeSet in Java

Leave a Reply

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