dsa

Java BufferedReader

In this tutorial, we will learn about the Java BufferedReader, its constructors and its methods with the help of an example.

Java BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Constructors of BufferedReader

Methods

MethodsDescription
void close()Closes the stream and releases any system resources associated with it.
Stream<String> lines()Returns a Stream, the elements of which are lines read from this BufferedReader.
void mark(int readAheadLimit)Marks the present position in the stream.
boolean markSupported()Tells whether this stream supports the mark() operation, which it does.
int read()Reads a single character.
int read(char[] cbuf, int off, int len)Reads characters into a portion of an array.
String readLine()Reads a line of text.
boolean ready()Tells whether this stream is ready to be read.
void reset()Resets the stream to the most recent mark.
long skip(long n)Skips characters.

Examples :

Suppose we have a file named input.txt with the following content:

This file consists of a single line.


import java.io.FileReader;
import java.io.BufferedReader;

class Codemistic 
{
  	public static void main(String[] args) 
	{

    		// Creates an array of character
    		char[] array = new char[100];

    		try 
		{
      			// Creates a FileReader
      			FileReader file = new FileReader("input.txt");

      			// Creates a BufferedReader
      			BufferedReader input = new BufferedReader(file);

      			// Reads characters
      			input.read(array);
      			System.out.println("Data in the file: ");
      			System.out.println(array);

      			// Closes the reader
      			input.close();
    		}
    		catch(Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}


Output :

Data in the file:
This file consists of a single line.