BufferedReader ready() in Java

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

Syntax:

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

This method tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.

Parameters: NA

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

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        System.out.println(bufferedReader.ready());
        bufferedReader.close();

    }
}

Output:

true


Approach 2: IOException

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        bufferedReader.close();
        System.out.println(bufferedReader.ready());

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedReader.ensureOpen(BufferedReader.java:122) at java.base/java.io.BufferedReader.ready(BufferedReader.java:447)


No comments:

Post a Comment