Write a Java program that displays the number of characters, lines and words in a text file.

//Program to count number of lines,characters,and words in a text file
import java.util.*;
import java.io.*;
class Cfile
{
            public static void main(String args[])throws IOException
            {
                        int nl=1,nw=0;           
                        char ch;
                        Scanner scr=new Scanner(System.in);
                        System.out.print(“nEnter File name: “);
                        String str=scr.nextLine();
                        FileInputStream f=new FileInputStream(str);
                        int n=f.available();
                        for(int i=0;i<n;i++)
                        {
                                    ch=(char)f.read();
                                    if(ch==’n’)
                                    nl++;
                                    else if(ch==’ ‘)
                                                nw++;
                                                                       
                        }
                        System.out.println(“nNumber of lines : “+nl);
                        System.out.println(“nNumber of words : “+(nl+nw));
                        System.out.println(“nNumber of characters : “+n);
                       
            }
}
Output:
Enter File name: raj.txt
Number of lines : 3
Number of words : 3

Number of characters : 26

Leave a Reply

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

Enable Notifications OK No thanks