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
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.
This article seems like a practical guide for learning how to implement a Java program to count characters, lines, and words in a text file. The fact that it provides a Java program example is really helpful for understanding how to apply the concept. It sounds like a useful resource for anyone working with file handling in Java.
Thank you for this informative post.
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.
yes
is it executable code
Yes. It is executable code.