Signup/Sign In

Java FilterReader skip() Method

In this tutorial, we will learn about the skip() method of the FilterReader class in Java. This method, when called, skips the provided n number of characters from this filter reader. It is a non-static method, available in the java.io package, which can only be accessed using class objects, and throws an IOException when accessed using the class name.

Syntax

Below is the syntax declaration of this method. It takes the n number of characters to be skipped as a parameter and returns the total number of characters skipped.

public long skip(long n)

Example 1: Skip Characters in Java

In this example, we will use the method skip() to skip some characters from the stream while reading. here we are calling this method when each time we read from the stream so we will get the output as alternate characters of the stream.

import java.io.FileReader;
import java.io.FilterReader;
import java.io.Reader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			Reader reader = new FileReader("E:\\studytonight\\output.txt");  
			FilterReader filterReader = new FilterReader(reader) {};  
			int i;  
			while ((i = filterReader.read()) != -1) 
			{  
				System.out.print((char) i);  
				filterReader.skip(1);
			}  
			filterReader.close();  
			reader.close();  
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


1 3 5 7 9

output.txt

1 2 3 4 5 6 7 8 9 10

Example 1: Skip Characters in Java

By using the skip() method, we can skip multiple characters at a time, for example in the given below program, we call skip() method and passed 4 as a parameter to skip so it will skip the first 4 characters from the stream and start reading from the fifth character.

import java.io.FileReader;
import java.io.FilterReader;
import java.io.Reader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			Reader reader = new FileReader("E:\\studytonight\\output.txt");  
			FilterReader filterReader = new FilterReader(reader) {};  
			int i;  			
			filterReader.skip(4);
			while ((i = filterReader.read()) != -1) 
			{  
				System.out.print((char) i);  
			}  
			filterReader.close();  
			reader.close();  
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


tonight

output.txt

Studytonight

Conclusion

In this tutorial, we learned about the skip() method of the FilterReader class in Java, which is used to skip a given number of characters in the stream, by taking the number of characters to be skipped as a parameter and returning the actual number of characters skipped.



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.