Monday, 10 March 2025

Write a java program to count number of Lines, words and characters from a given file

 

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class FileStatistics {


    public static void main(String[] args) {

        if (args.length != 1) {

            System.out.println("Usage: java FileStatistics <filename>");

            return;

        }


        String filename = args[0];

        int lineCount = 0;

        int wordCount = 0;

        int charCount = 0;


        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {

            String line;

            while ((line = br.readLine()) != null) {

                lineCount++;

                charCount += line.length();

                wordCount += line.split("\\s+").length;

            }


            System.out.println("Number of lines: " + lineCount);

            System.out.println("Number of words: " + wordCount);

            System.out.println("Number of characters: " + charCount);


        } catch (IOException e) {

            System.out.println("An error occurred while reading the file: " + e.getMessage());

        }

    }

}