Introduction
Here I will create a sample program to count words, paragraphs, sentences, characters, white spaces in a text file using Java programming language.
In this tutorial I will read a simple text file and count number of words, paragraphs, characters etc.
Prerequisites
Java
Count in File
Now I will create Java program to count words, paragraphs, white spaces etc.
The below source code simply presents a method which takes a File input and read each line from the file and count the desired things.
In the below code I have used different separators for counting the words, paragraphs, sentences, etc.
package com.roytuts.java.count.word.para.sentence.whitespace.text.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaCountWordParaSentenceWhitespaceTextFile {
public static void main(String[] args) throws IOException {
countWordParaSentenceWhitespaceTextFile(new File("sample.txt"));
}
public static void countWordParaSentenceWhitespaceTextFile(final File file) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;
while ((line = br.readLine()) != null) {
if (line.equals("")) {
paragraphCount++;
} else {
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
whitespaceCount += countWord - 1;
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
}
}
br.close();
System.out.println("Total number of words = " + countWord);
System.out.println("Total number of sentences = " + sentenceCount);
System.out.println("Total number of characters = " + characterCount);
System.out.println("Total number of paragraphs = " + paragraphCount);
System.out.println("Total number of whitespaces = " + whitespaceCount);
}
}
Testing the Program
Now I will just pass a sample text file and call the above method. The sample.txt file is kept on the root folder of the project name or the project folder.
public static void main(String[] args) throws IOException {
countWordParaSentenceWhitespaceTextFile(new File("sample.txt"));
}
Executing the above main method will give you below output:
Total number of words = 53
Total number of sentences = 5
Total number of characters = 276
Total number of paragraphs = 3
Total number of whitespaces = 137
That’s all about how to count words, paragraphs, sentences, white spaces by reading a text file.