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

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

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

  1. 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++; }
    }

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in