FilterReader reset() in Java

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

Syntax:

void java.io.FilterReader.reset() throws IOException

This method resets the stream.

Parameters: NA

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

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

        filterReader.reset();
        System.out.println("Successfully reset the stream");
        filterReader.close();
    }
}

Output:

Successfully reset the stream


Approach 2: IOException 

Java

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

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

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

        filterReader.close();
        filterReader.reset();
        System.out.println("Successfully reset the stream");
        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.reset(StringReader.java:188) at java.base/java.io.FilterReader.reset(FilterReader.java:118)


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.

skip(long)This method skips characters.


No comments:

Post a Comment