Signup/Sign In

Java FileInputStream skip() Method

In this tutorial, we will learn about the skip() method of the FileInputStream class in Java. This method is used to skip and discard the given number of bytes of data from this File Input Stream. It is a non-static method, available in the java.io package.

Syntax

This is the syntax declaration of this method. It accepts the 'n' number of bytes to be skipped as a parameter and returns the exact number of bytes skipped.

public long skip(long n)

Example 1: Skip bytes using FileInputStream in Java

Let's see an example where we use the skip() method of FileInputStream to skip bytes of data. See the example below.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		int i;
		try 
		{
			InputStream inputStream = new FileInputStream("E:\\studytonight\\output.txt");
			while ((i = inputStream.read()) != -1)
			{
				char c = (char) i;
				System.out.print(c + " ");
				inputStream.skip(1);
			}

			inputStream.close();
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}  
}


Hlosuyoih

Example 2: Skip bytes using FileInputStream in Java

Let's see another example where we use the skip() method of FileInputStream to skip bytes of data from a file stream. See the example below.

import java.io.*;
public class Studytonight {
 public static void main(String[] args) throws Exception {
  FileInputStream st = null;
  int count = 0;
  try {
   st = new FileInputStream("E:\Studytonight\output.txt");
   while ((count = st.read()) != -1) {   
    count = st.read();    
    byte b = (byte) count;    
    System.out.println("st.read(): " + b);
    long skip_byte = st.skip(2);
    System.out.println("st.skip(2): " + skip_byte);
    System.out.println();
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   
   if (st != null) {
    st.close();
   }
  }
 }
}


st.read(): 4
st.skip(2): 2

st.read(): 97
st.skip(2): 2

st.read(): 111
st.skip(2): 2

st.read(): 33
st.skip(2): 2

Conclusion:

In this tutorial, we learned about the skip() method of the FileInputStream class in Java, which skips the given number of bytes of data from the current input stream and returns the actual number of bytes skipped. It is accessible with the class object only and if we try to access the method with the class name then we will get an error.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.