Java.io.BufferedReader.read() Method
Advertisements
Description
The java.io.BufferedReader.read() method reads a single character from this buffered reader.
Declaration
Following is the declaration for java.io.BufferedReader.read() method
public int read()
Parameters
NA
Return Value
The method returns a character as an integer. If the end of the stream has been reached the method returns -1.
Exception
IOException -- -- if an I/O error occurs
Example
The following example shows the usage of public int read() method.
package com.tutorialspoint;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BufferedReaderDemo {
public static void main(String[] args) throws Exception {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream text.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
int value=0;
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;
// prints character
System.out.println(c);
}
}catch(Exception e){
e.printStackTrace();
}finally{
// releases resources associated with the streams
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
Assuming we have a text file c:/test.txt, which has the following content. This will 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:
A B C D E