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

Friday, October 2nd, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.io.*;
class wordcount
{
	public static int words=0;
	public static int lines=0;
	public static int chars=0;
	public static void wc(InputStreamReader isr)throws IOException
	{
		int c=0;
		boolean lastwhite=true;
		while((c=isr.read())!=-1)
		{
			chars++;
			if(c=='\n')
				lines++;
			if(c=='\t' || c==' ' || c=='\n')
				++words;
			if(chars!=0)
				++chars;
		}	
       }
	public static void main(String[] args)
	{
		FileReader fr;
		try
		{
			if(args.length==0)
			{
				wc(new InputStreamReader(System.in));
			}
			else
			{
				for(int i=0;i<args.length;i++)
				{
					fr=new FileReader(args[i]);
					wc(fr);
				}
			}
 
		}
		catch(IOException ie)
		{
			return;
		}
		System.out.println(lines+" "+words+" "+chars);
	}
}

Output:

This is II CSE
1 4 32

Draw the frequency response
1 4 58

Avatar Image

Author Name :
Ranjith

Total : 0 Comment


Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup