Java
Java

 

 

Introduction

In this tutorial, we will demonstrate how to read the contents of a file in Java and display them on the console. This is a common task when dealing with file input/output operations in programming. Understanding how to read from a file is an essential skill for managing data, processing logs, or handling any file-based data in software development.

Objective

The objective of this program is to:

  • Read a text file using Java.
  • Display the contents of the file on the console.
  • Learn the use of Java file handling classes like FileReader, BufferedReader, and IOException.

Java Program to Read and Display File Contents

import java.io.*;

public class ReadFileExample {
    public static void main(String[] args) {
        // Define the file path (modify this based on your file location)
        String filePath = "example.txt"; // Replace with your file name

        // Create a BufferedReader to read the file
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;

            // Read each line of the file and display it
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            // Handle the exception if the file is not found or there is an error reading it
            System.err.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}

Explanation of the Program Structure

The program is simple and straightforward. Here’s a breakdown of the structure:

  • Imports: The program imports the necessary classes: FileReader, BufferedReader, and IOException. These classes are essential for reading files in Java.
  • File Path: The file path is defined as a string. You should replace example.txt with the actual path of your file.
  • BufferedReader: This is used to read text from a character-based input stream. It reads the file line by line, which is efficient for large files.
  • try-with-resources: This syntax ensures that the resources (BufferedReader) are automatically closed after use, even if an exception occurs. It’s a good practice to use this to avoid memory leaks.
  • Exception Handling: The program uses a try-catch block to handle any potential IOExceptions, which may occur if the file doesn’t exist or there’s an error reading it.

How to Run the Program

To run this Java program, follow these steps:

  1. Ensure you have Java installed on your machine. You can download it from the official Oracle website.
  2. Save the program code in a file named ReadFileExample.java.
  3. Open a terminal (command prompt) and navigate to the directory where you saved the file.
  4. Compile the Java file by running the command:
    javac ReadFileExample.java
  5. Run the compiled Java program:
    java ReadFileExample
  6. Ensure that the file you want to read (e.g., example.txt) is in the same directory, or provide the absolute path to the file in the code.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)