Monday, 10 March 2025

Write a Java program to count number of digits, spaces and characters from a file.


import java.io.*;


public class FileCharacterCounter {

    public static void main(String[] args) {

        // Specify the file path

        String filePath = "sample.txt";


        int digitCount = 0;

        int spaceCount = 0;

        int charCount = 0;


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

            int ch;

            while ((ch = br.read()) != -1) {

                if (Character.isDigit(ch)) {

                    digitCount++;

                } else if (Character.isWhitespace(ch)) {

                    spaceCount++;

                } else {

                    charCount++;

                }

            }


            System.out.println("Number of Digits: " + digitCount);

            System.out.println("Number of Spaces: " + spaceCount);

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

        } catch (IOException e) {

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

        }

    }

}