Write a Java program that displays the number of characters, lines and words in a text file.
Program Code:
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);
}
}
Post A Comment:
0 comments: