Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Files. 5 Comments on Java program to display the number of characters lines and words in a text file

In this article we will learn to implement a Java program to display the number of characters lines and words in a text file. A Java program is provided below that displays the number of characters, lines and words in a text file.

 

import java.io.*;
class FileDemo
{
	public static void main(String args[])
	{
		try
		{
			int lines=0,chars=0,words=0;
			int code=0;
			FileInputStream fis = new FileInputStream("sample.txt");
			while(fis.available()!=0)
			{
				code = fis.read();
				if(code!=10)
				chars++;
				if(code==32)
				words++;
				if(code==13)
				{
					lines++;
					words++;
				}
			}
			System.out.println("No.of characters = "+chars);
			System.out.println("No.of words = "+(words+1));
			System.out.println("No.of lines = "+(lines+1));
			fis.close();
		}
		catch(FileNotFoundException e)
		{
			System.out.println("Cannot find the specified file...");
		}
		catch(IOException i)
		{
			System.out.println("Cannot read file...");
		}
	}
}

 

Content in sample.txt file is:

He is
a good
boy

 

Input and output for the above program is as follows:

No.of characters = 16
No.of words = 5
No.of lines = 3

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

5 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

fis.available()

What do you mean?

    Hi,

    The available() method returns the number of remaining bytes in the file. So, if that method a non-zero value, that means there is still content available in the file that needs to be read.

is it executable code

Leave a Reply

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