FilterReader mark(int) in Java

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

Syntax:

void java.io.FilterReader.mark(int readAheadLimit) throws IOException

This method takes one argument. This method marks the present position in the stream.

Parameters: One parameter is required for this method.

readAheadLimit: Limit the number of characters that may be read while still preserving the mark.

After reading this many characters, attempting to reset the stream may fail.

Returns: NA

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 FilterReadermark {
    public static void main(String[] args) throws IOException {

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

        int readAheadLimit = 1;
        filterReader.mark(readAheadLimit);
        System.out.println("Successfully marked the read limit");
        filterReader.close();
    }
}

Output:

Successfully marked the read limit


Approach 2: IOException 

Java

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

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

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

        int readAheadLimit = 1;
        filterReader.close();
        filterReader.mark(readAheadLimit);
        System.out.println("Successfully marked the read limit");
        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.mark(StringReader.java:175) at java.base/java.io.FilterReader.mark(FilterReader.java:109)


Some more methods of FilterReader class.

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

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.

skip(long): This method skips characters.

No comments:

Post a Comment