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

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

4 Responses to “Java program that displays the number of characters, lines and words in a text file”

  1. sudhansu sekhar nayak

    Sir plz don’t mind . this code is not work properly.

    Reply
  2. Raj Kumar Sharma

    Replace the wc() function by this-

    public static void wc(InputStreamReader isr)throws IOException {
    int c=0;
    boolean lastwhite=true;
    while((c=isr.read())!=-1) {
    if(c==’\n’)
    { lines++; ++words; }
    else
    if(c!=’\r’)chars++;
    if(c==’\t’ || c==’ ‘)
    ++words;
    }
    if(chars>0) { words++; lines++; }
    }

    Reply

Leave a Reply