FilterReader ready() in Java

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

Syntax:

boolean java.io.FilterReader.ready() throws IOException

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

Parameters: NA

Returns: True if the next read() is guaranteed not to block for input,false otherwise.

Note that returning false does not guarantee that the next read will block.

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

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

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

Output:

true


Approach 2: IOException 

Java

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

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

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

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


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.

reset(): This method resets the stream.

skip(long): This method skips characters.


No comments:

Post a Comment