How to count words, paragraphs, sentences, characters, white spaces in a text file using Java

Introduction

Here we will create a sample program to count words, paragraphs, sentences, characters, white spaces in a text file using Java programming language.

In this tutorial we will read a simple text file and count number of words, paragraphs, characters etc.

Prerequisites

Java

Count in File

Now we 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.

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;
		}

	}

	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 we will just pass a sample text file and call the above method.

public static void main(String[] args) throws IOException {
	countWordParaSentenceWhitespaceTextFile(new File("C:/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.

Download Source Code

Thanks for reading.

Related posts

Leave a Comment