FilterReader read() in Java

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

Syntax:

int java.io.FilterReader.read() throws IOException

This method reads a single character.

Parameters: NA

Returns: The character read, as an integer in the range 0 to 65535(0x00-0xffff), or -1 if the end of the stream has been reached.

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

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

        System.out.println(filterReader.read());
        filterReader.close();
    }
}

Output:

104


Approach 2: IOException 

Java

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

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

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

        filterReader.close();
        System.out.println(filterReader.read());
        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.read(StringReader.java:69) at java.base/java.io.FilterReader.read(FilterReader.java:65)


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(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