Skipping data while reading

In this post under Apache Commons IO, I will explain with example how to skip certain amount data while reading.

We can use static “skip” method available as part of “IOUtils” class.

This method takes two arguments
1) the reader from where it is reading data. The reader can be byte or character stream
2) the number of bytes or characters to skip

Below is the main code showing its usage.

Main class

package ioutils;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Example11 {
    public static void main(String[] args) throws IOException {
        String input = "No man is a true believer unless he desires for his brother that which he desires for himself. -Prophet\n" +
                "\n" +
                "Limits are what separates us from animals. -Satyameva Jayate\n" +
                "\n" +
                "For a new start, it is necessary to end what is going on - Murder 3\n" +
                "\n" +
                "A person gets a reply from the place where he is scared to go - Murder 3\n" +
                "\n" +
                "The strong man who has known power all his life, may lose respect for that power, but a weak man knows the value of strength, and knows compassion. - Captain America The first Avenger\n" +
                "\n" +
                "A person is a fool if he knows just the truth and not the difference between the truth and the lie - Badla";

        try(StringReader stringReader = new StringReader(input)) {
            char[] charBuffer = new char[100];
            int count = IOUtils.read(stringReader, charBuffer);
            while(count > 0) {
                IOUtils.write(charBuffer, System.out, StandardCharsets.UTF_8);
                IOUtils.skip(stringReader, 50);
                Arrays.fill(charBuffer, ' ');
                count = IOUtils.read(stringReader, charBuffer);
            }
        }
    }
}

In the above code, at line 12, I define the String variable “input” which will have the data to be read.

In the try-with-resource block, I create an instance of “StringReader” through which the data has to be read.

At line 25, I create character array of size 100.

In a while loop I read data from the StringReader and whatever data is read it is printed to console.

At line 29, I call “skip” method to skip 50 characters from the reader.

In this way we can skip data while reading.

Leave a comment