Logo

Who is talking?

Archive

Write a Java program to read console data using bufferedreader API

5 months ago | Subodh Gupta: Subodh's Blog

BufferedReader is a class which simplifies reading text from a character input stream. It buffers the characters in order to enable efficient reading of text data. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, // BufferedReader in = new BufferedReader(new FileReader("foo.in")); will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class BufferedReaderExample {  public static void main(String[] s) throws IOException {    // Wrap System.in with InputStreamReader followed by BufferedReader    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));    System.out.print("Enter Name: ");      // Finally read from bufferedReader     String name = bufferedReader.readLine();    System.out.println("Name: " + name);  }}