FilterReader skip(long) in Java

skip(long): This method is available in the java.io.FilterReader class of Java.

Syntax:

long java.io.FilterReader.skip(long n) throws IOException

This method takes one argument. This method skips characters.

Parameters: One parameter is required for this method.

n: The number of characters to skip.

Returns: The number of characters actually skipped.

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class FilterReaderskip {
    public static void main(String[] args) throws IOException {

        Reader reader = new StringReader("hello");
        FilterReader filterReader = new FilterReader(reader) {
        };

        long n = 100L;
        System.out.println(filterReader.skip(n));
        filterReader.close();
    }
}

Output:

5


Approach 2: IOException

Java

import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class FilterReaderskip {
    public static void main(String[] args) throws IOException {

        Reader reader = new StringReader("hello");
        FilterReader filterReader = new FilterReader(reader) {
        };

        long n = 100L;
        filterReader.close();
        System.out.println(filterReader.skip(n));
        filterReader.close();
    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.StringReader.ensureOpen(StringReader.java:56) at java.base/java.io.StringReader.skip(StringReader.java:125) at java.base/java.io.FilterReader.skip(FilterReader.java:84)


Some more methods of FilterReader class.

close(): This method closes the stream and releases any system resources associated with it.

mark(int): This method marks the present position in the stream.

markSupported(): This method tells whether this stream supports the mark() operation.

read(): This method reads a single character.

read(char[], int, int): This method reads characters into a portion of an array.

ready(): This method tells whether this stream is ready to be read.

reset(): This method resets the stream.


No comments:

Post a Comment