java.io.BufferedReader ready()

Description :

This java tutorial shows how to use the ready() method of Scanner class of java.io package. This method returns a boolean data type, true if the buffer is not empty which signifies that the stream is ready to be read otherwise false.

Method Syntax :

public boolean ready() throws IOException

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method simply returns true 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.

Compatibility Version :

Requires Java 1.1 and up

Exception :

None

Discussion :

The BufferedReader ready() method overrides the inherited method of Reader class. This method is used to flag down if the stream is ready to be read.

Java Code Example :

This java example source code demonstrates the use of ready() method of BufferedReader class. Basically the code asks for the user address from the console and then uses the ready method to check if the character stream is ready. If the stream is ready, we then prints out the address using the BufferedReader nextLine() method.

package com.javatutorialhq.java.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Scanner;

/*
 * Java example source code that uses the ready() method of
 * BufferedReader class to check if the stream is ready to be read
 * This example java program reads a user input and then
 * use the ready() method as a means to check if the character stream
 * is ready.
 */

public class BufferedReaderReady {

	public static void main(String[] args) {

		System.out.print("What is your address? ");

		// Get the user input		
		Scanner s = new Scanner(System.in);

		// declare the BufferedReader Class
		BufferedReader reader = new BufferedReader(new StringReader(s.nextLine()));

		// catch the possible IOException by the readLine() method
		try {

			// check if stream is ready to be read			
			if(reader.ready()){

				// print the text read by the BufferedReader
				System.out.println("String read from console input:" + reader.readLine());	
			}

			// close the BufferedReader object
			s.close();
			reader.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Sample Output :

Running the ready() method example source code of BufferedReader class will give you the following output

What is your address? Manila Philippines
String read from console input:Manila Philippines

Similar Method :

  • N/A

Suggested Reading List :

References :