Saturday, 4 November 2023

Write a java program to count number of digits, spaces and characters from a file.-core java slip24

 

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

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class FileCharacterCount {

    public static void main(String[] args) {

        String fileName = "your_file.txt"; // Replace with the actual file path

 

        int digitCount = 0;

        int spaceCount = 0;

        int characterCount = 0;

 

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

            int c;

            while ((c = reader.read()) != -1) {

                char ch = (char) c;

                if (Character.isDigit(ch)) {

                    digitCount++;

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

                    spaceCount++;

                }

                characterCount++;

            }

        } catch (IOException e) {

            System.err.println("An error occurred while reading the file.");

            e.printStackTrace();

        }

 

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

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

        System.out.println("Characters: " + characterCount);

    }

}