Reader

Reader is an abstract class in Java used for reading character streams. It is the base class for all classes that read character data, such as BufferedReader, FileReader, StringReader, etc.It plays the character-based equivalent of the InputStream, which deals with byte-based streams.

Commonly Used Methods

Simple Program – Read from a File Using FileReader

Read and print the contents of a text file using FileReader.

import java.io.*;

public class SimpleReaderDemo {
    public static void main(String[] args) {
        try {
            Reader reader = new FileReader("message.txt");
            int data;
            while ((data = reader.read()) != -1) {
                System.out.print((char) data);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Sample message.txt:

Welcome to JavaReader!

Problem Statement:

LotusJavaPrince wants to create a feature where he can read user bio-data stored in a .txt file line by line and display it. Mahesh helps by using BufferedReader for efficient reading.

import java.io.*;

public class BioDataReader {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("bio.txt"));

            String line;
            System.out.println("Reading User Bio:");
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
        } catch (IOException e) {
            System.out.println("Error reading file.");
            e.printStackTrace();
        }
    }
}

Sample bio.txt:

Name: LotusJavaPrince
Occupation: Software Architect
Location: JavaPlanet
Skills: Java, Spring, Design PatternsCode language: HTTP (http)

Output:

Reading User Bio:
Name: LotusJavaPrince
Occupation: Software Architect
Location: JavaPlanet
Skills: Java, Spring, Design Patterns

The Reader class in Java is a core part of the character-based input stream hierarchy, designed to efficiently handle text data in a platform-independent manner. As an abstract superclass, it provides a flexible interface for reading character streams from various sources such as files, strings, or even network connections.

Scroll to Top