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

Program Code in JAVA:
import java.io.*;
import java.util.*;
class FileCount
{
public static void main(String[] args) throws Exception
{
String fname;
System.out.println("Enter a filename:");
DataInputStream dis=new DataInputStream(System.in);
fname=dis.readLine();
FileReader f=new FileReader(fname);
BufferedReader br=new BufferedReader(f);
String str;
int words=0,lines=0,chars=0;
while((str=br.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(str);
lines++;
words+=st.countTokens();
int i=0,n;
n=str.length();
for(i=0;i<n;i++)
{
char ch=str.charAt(i);
if(ch!=' ')
chars++;
}
}
System.out.println("the number of lines in the file are = "+lines);
System.out.println("the number of words in the file are = "+words);
System.out.println("the number of characters in the file are = "+chars);
}
}

Program Output:
c:\java>javac FileCount.java
c:\java>java FileCount
Enter a filename:
FileCount.java
the number of lines in the file are = 34
the number of words in the file are = 85
the number of characters in the file are = 749
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: