-
Notifications
You must be signed in to change notification settings - Fork 0
Reader & BufferedReader Class
Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both.
Some of the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.
Let's see the declaration for Java.io.BufferedReader class:
public class BufferedReader extends Reader
Java BufferedReader class constructors Constructor Description BufferedReader(Reader rd) It is used to create a buffered character input stream that uses the default size for an input buffer. BufferedReader(Reader rd, int size) It is used to create a buffered character input stream that uses the specified size for an input buffer.
Java BufferedReader Example
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Reading data from console by InputStreamReader and BufferedReader
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}