Monday, 10 March 2025

Write a Java program to display contents of file in reverse order


import java.io.FileReader;

import java.io.IOException;


public class ReverseFileContent {

    public static void main(String[] args) {

        String fileName = "input.txt"; // File to read


        try (FileReader reader = new FileReader(fileName)) {

            StringBuilder content = new StringBuilder();

            int character;

            

            while ((character = reader.read()) != -1) { // Read each character

                content.append((char) character); 

            }

            

            // Reverse the content and display it

            System.out.println("Reversed Content:\n" + content.reverse());

        } catch (IOException e) {

            System.out.println("Error reading file: " + e.getMessage());

        }

    }

}