Java.io.InputStreamReader.ready() Method
Advertisements
Description
The java.io.InputStreamReader.ready() method tells whether this stream is ready to be read.
Declaration
Following is the declaration for java.io.InputStreamReader.ready() method:
public boolean ready()
Parameters
NA
Return Value
The method returns true if the next read is guaranteed not to block for input, else false.
Exception
IOException -- If an I/O error occurs
Example
The following example shows the usage of java.io.InputStreamReader.ready() method.
package com.tutorialspoint;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
InputStreamReader isr =null;
boolean bool = false;
int i;
char c;
try {
// new input stream reader is created
fis = new FileInputStream("C:/test.txt");
isr = new InputStreamReader(fis);
// reads into the char buffer
while((i=isr.read())!=-1)
{
// converts int to char
c=(char)i;
// prints the character
System.out.println("Character read: "+c);
// true if the next read is guaranteed
bool = isr.ready();
// prints
System.out.println("Ready to read: "+bool);
}
} catch (Exception e) {
// print error
e.printStackTrace();
} finally {
// closes the stream and releases resources associated
if(fis!=null)
fis.close();
if(isr!=null)
isr.close();
}
}
}
Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:
ABCDE
Let us compile and run the above program, this will produce the following result:
Character read: A Ready to read: true Character read: B Ready to read: true Character read: C Ready to read: true Character read: D Ready to read: true Character read: E Ready to read: false