AppDividend
Latest Code Tutorials

Java BufferedReader Class Tutorial With Example

0

Java BufferedReader Class Tutorial With Example is today’s topic. The BufferedReader class extends the Reader class in Java and is used to take input from the input stream of characters. The BufferedReader class does not read byte by byte or character by character, it instead creates a buffer and loads some content to be read in this buffer (depending on the size of the buffer) and then reads from this buffer. Reading from the buffer is comparatively fast as in reading character by character, a read operation needs to be performed for every character.

Java BufferedReader Class

Therefore, the BufferReader class is more efficient. The default size for the buffer will be used if a specific size is not provided to the constructor. The BufferedReader can be used instead of DataInputStreams for input.

Diagram showing the working of BufferedReader class:

Java BufferedReader Class

#Constructors:

  • BufferedReader(Reader rd): It is used to create the buffered character input stream with the buffer of default size. It takes the object of Reader class or any of its child class.

  • BufferedReader(Reader rd, int s): It is used to create the buffered character input stream with the buffer of specified size ‘s’.

#Methods of BufferReader Class

#int read()

This method will read a single character from the buffer as an Integer. The end of file is represented as -1. It throws IOException.

Syntax : public int read() throws java.io.IOException

#int read(char[ ] arr, int i, int len)

This method is used to store the read content in the Character array. The i in the argument specifies the offset in the array from which the characters will be started to get stored. len specifies the maximum number of characters to read.

Syntax : public int read(char[ ] arr, int i, int len) throws java.io.IOException

#String readLine()

This method will read characters until the escape characters ( \n or \r ) are not encountered and return the result as a string. It throws IOException.

Syntax : public String readLine() throws java.io.IOException

#long skip(long num)

This method will skip the specified number of characters while reading. If num is negative, It will throw IllegalArgumentException. It also throws IOException.

Syntax: public long skip(long num) throws java.io.IOException

#boolean ready()

This method will return true if the buffered character input stream is ready to be read, that is if the buffer is nonempty. Otherwise, it will return it will false. It throws IOException.

Syntax : public boolean ready() throws java.io.IOException

#boolean markSupported()

This method will return true if this stream supports the mark() method.

Syntax: public boolean markSupported()

#void mark(int num)

This method will set the current position of the stream as a checkpoint. The num in argument specifies the number of characters to be read while marking the current position. It throws IOException.

Syntax: public void (int num) throws java.io.IOException 

#void reset()

This method will reset the current position to the last checkpoint created using the mark() method. It would throw the IOException if no mark were created.

Syntax : public void reset() throws java.io.IOException 

#void close()

This method will close the buffered character input stream, releasing all the associated resources.

Syntax : public void close() throws java.io.IOException 

#Stream<String> lines()

This method will return a stream having the lines from the BufferReader.

Syntax : public Stream<String> lines( )

#Programs

See the following program to take the input from the console using BufferedReader class.

import java.io.*;

class Example1
{
  //IOException is a checked exception, so it needs to be thrown
  public static void main(String[] args) throws IOException
  {
    String sports;
    
    //creating an inputStreamReader for user input
    InputStreamReader stream=new InputStreamReader(System.in);
    
    //creating the buffered character input stream. The argument contains the InputSreamReader object as it is a child class of Reader class
    BufferedReader reader=new BufferedReader(stream);              
    System.out.println("what is your favourite sports?");
    System.out.print("Enter: ");
    
    //reading from console    
    sports=reader.readLine();                                     
    System.out.print("\nYour favourite sports is: ");
    System.out.println(sports);
  }
}

See the following output.

 

Methods of BufferReader Class

See the following program to read a file using BufferedReader class.

import java.io.*;

class Example2
{
  public static void main(String[] args) throws IOException
  {
    int c;
    FileReader file=new FileReader("file.txt");              //creating the FileReader for reading the file
    BufferedReader reader= new BufferedReader(file);
    System.out.println("The content of the file is:\n");
    while((c=reader.read())!=-1)                             //reading the character from the buffer and checking for end of the file
    {
      System.out.print((char)c);                             //read method returns integer, so it must be typecasted into character
    }

    System.out.println();
  }
}

See the following output.

 

Constructors of BufferReader Class

See the following example.

Program to skip certain characters while reading and storing the read result in the character array.

import java.io.*;

class Example3
{
  public static void main(String[] args) throws IOException
  {
    char[] arr=new char[37];
    int offset=0;
    int len=37;
    long skip_ch=40;

    FileReader file=new FileReader("file.txt");
    BufferedReader reader= new BufferedReader(file);

    //skips certain characters
    reader.skip(skip_ch);

    //read from the file using buffer and store the result in character array
    reader.read(arr,offset,len);

    //print the array
    for(char c: arr)
      System.out.print(c);

    //close the streams
    reader.close();
    file.close();

    System.out.println();
  }
}

See the following output.

 

BufferedReader Class in Java

#Difference b/w Scanner and BufferReader Class in Java

The java.util.Scanner class is the simple text scanner which can parse the primitive types and strings. It internally uses the regular expressions to read different types.

Java.io.BufferedReader class reads text from the character-input stream, buffering characters to provide for the efficient reading of the sequence of characters.

BufferedReader is the synchronous while Scanner is not synchronous. BufferedReader should be used if we are working with multiple threads.

BufferedReader has a ridiculously larger buffer memory than Scanner.

The Scanner has the minimal buffer (1KB char buffer) as opposed to a BufferedReader (8KB byte buffer), but it’s more than enough.

BufferedReader is the bit faster as compared to scanner because a scanner does parsing of input data and BufferedReader reads the sequence of characters.

Finally, Java BufferedReader Class Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.