Java - BufferedReader read() method



Description

The Java BufferedReader read() method reads a single character from this buffered reader. read() method reads one character at a time and returns its integer Unicode value. It returns -1 when the end of the stream is reached.

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

Assumption

Assuming we have a text file example.txt, which has the following content. This file will be used as an input for our example programs −

ABCDE 

Example - Using read() method

The following example shows the usage of Java BufferedReader read() method.

BufferedReaderDemo.java

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 example.txt for reading purpose.
         is = new FileInputStream("example.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();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

A
B
C
D
E

Example - Reading and Printing Each Character

The following example shows the usage of Java BufferedReader read() method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      String input = "Hello, World!";

      // Initialize BufferedReader with a StringReader
      try (BufferedReader reader = new BufferedReader(new StringReader(input))) {
         int character;

         System.out.println("Reading characters one by one:");

         // Read each character until the end of the stream
         while ((character = reader.read()) != -1) {
            // Print the character (cast the integer to char)
            System.out.print((char) character);
         }
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Reading characters one by one:
Hello, World!

Explanation

  • A BufferedReader is initialized with a StringReader containing the string "Hello, World!".

  • The read() method reads one character at a time from the stream.

  • The returned integer is cast to a char to display the actual character.

  • The loop continues until the end of the stream is reached (read() returns -1).

Example - Counting Specific Characters

The following example shows the usage of Java BufferedReader read() method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      String input = "Java is fun! Isn't it?";

      // Initialize BufferedReader with a StringReader
      try (BufferedReader reader = new BufferedReader(new StringReader(input))) {
         int character;
         int vowelCount = 0;

         // Count vowels while reading characters
         while ((character = reader.read()) != -1) {
            char ch = (char) character; // Cast integer to char
            if ("AEIOUaeiou".indexOf(ch) != -1) {
               vowelCount++;
            }
         }

         System.out.println("Total vowels in the input: " + vowelCount);
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Total vowels in the input: 6

Explanation

  • A BufferedReader is initialized with a StringReader containing the string "Java is fun! Isn't it?".

  • The read() method reads one character at a time and checks if it is a vowel.

  • Vowels are identified by checking if the character exists in the string "AEIOUaeiou".

  • The program counts the total number of vowels in the input.

Key Takeaways

  • Method Behavior

    • The read() method reads a single character from the stream and returns its integer Unicode value.

    • It returns -1 when the end of the stream is reached.

  • Use Cases

    • Example 1 demonstrates reading and displaying characters sequentially.

    • Example 2 demonstrates how the read() method can be used for specific tasks like counting characters or analyzing input.

All examples show practical applications of the single-character read() method in BufferedReader.

java_io_bufferedreader.htm
Advertisements