Java BufferedReader Class Example

BufferedReader class is used to read character stream.

BufferedReader Class Example

This program reads a text file named "sample.txt" and print output to console. The "sample.txt" contains below text in it.
 This example uses the try-with-resources statement to close the resources automatically.
This is the text content
import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;

/**
 * The class demonstrate the usage of BufferedReader class methods.
 * @author javaguides.net
 *
 */
public class BufferedReaderExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("sample.txt");
              BufferedReader br = new BufferedReader(fr);) {
              String sCurrentLine;

              while ((sCurrentLine = br.readLine()) != null) {
                   System.out.println(sCurrentLine);
              }
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}
Output:
This is the text content

Reference

https://www.javaguides.net/2018/08/bufferedreader-class-in-java.html


Comments