Count and print number of words and lines in a text file in Java

In this article, we will count and print number of words and lines in a text file i.e.;

From text file, we will be counting & printing

  • Number of lines
  • Number of words

 

Steps for counting words and lines:

  1. First write logic to read file from local drive location using BufferedReader & FileReader
  2. Read file line-by-line using while-loop and increase lineCount variable by 1 (starting from 0, already initialised at the top of method)
  3. For every line, split String using space as delimiter & assign it to temporary String[] array
  4. Get number of word count using length property of String[] array
  5. Now add word count to already initialized wordCount variable (starting from 0, already initialised at the top of method)
  6. Finally print lineCount & wordCount to console

 

Sample text file:

 

Let us move forward and write a simple Java program to demonstrate these steps

ReadCountPrintLinesAndWordsInTextFile.java

package in.bench.resources.count.print.occurences;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadCountPrintLinesAndWordsInTextFile {

	// main() method - entry point to start execution
	public static void main(String[] args) {

		// invoke to count & print for supplied file
		countAndPrintLineWord("D://WORKSPACE/TEST_WORKSPACE/Java_8_Project/BRN.txt");
	}

	/**
	 * this method count & prints number of lines & words in a text file
	 * @param fileName
	 */
	public static void countAndPrintLineWord(String fileName) {

		// local variables
		BufferedReader bufferedReader = null;
		String line = "";
		int lineCount = 0;
		int wordCount = 0 ;

		// Step 1: Read file from local drive location
		try {
			bufferedReader = new BufferedReader(new FileReader(fileName));

			// Step 2: Read line from file
			while ((line = bufferedReader.readLine()) != null) {

				// increase line count by 1
				lineCount++;

				// Step 3: split line using space as delimiter
				String[] words = line.split(" ");

				// Step 4 & 5: add word count length
				wordCount = wordCount + words.length;
			}

			// Step 6: print the count value of line & word
			System.out.println("Number of lines is : " + lineCount);
			System.out.println("Number of words is : " + wordCount);
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}
		finally {

			// close resources, if any
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			} 
			catch (IOException ioex) {
				ioex.printStackTrace();
			}
		}
	}
}

Output:

Number of lines is : 4
Number of words is : 41

 

Java 1.7 version onwards:

With the introduction of Java 1.7 version,

  • we can simplify the above code by removing finally blocks
  • replacing with try-with-resources statement
  • which takes care of automatic resource management i.e.;
  • auto-closing of opened resources without explicit closing inside finally block after necessary null-safety checks
  • thus, it improves readability of the code by reducing number of lines of code
  • let us re-write above program again with try-with-resources statement

ReadCountPrintLinesAndWordsInTextFile.java

package in.bench.resources.count.print.occurences;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadCountPrintLinesAndWordsInTextFile {

	// main() method - entry point to start execution
	public static void main(String[] args) {

		// invoke to count & print for supplied file
		countAndPrintLineWord("D://WORKSPACE/TEST_WORKSPACE/Java_8_Project/BRN.txt");
	}

	/**
	 * this method count & prints number of lines & words in a text file
	 * @param fileName
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void countAndPrintLineWord(String fileName) {

		// local variables
		String line = "";
		int lineCount = 0;
		int wordCount = 0 ;

		// Step 1: Read file from local drive location
		try(BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName))) {

			// Step 2: Read line from file
			while ((line = bufferedReader.readLine()) != null) {

				// increase line count by 1
				lineCount++;

				// Step 3: split line using space as delimiter
				String[] words = line.split(" ");

				// Step 4 & 5: add word count length
				wordCount = wordCount + words.length;
			}

			// Step 6: print the count value of line & word
			System.out.println("Number of lines is : " + lineCount);
			System.out.println("Number of words is : " + wordCount);
		}
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}
	}
}

Output:

Number of lines is : 4
Number of words is : 41

 

Hope, you found this article very helpful. If you any suggestion or want to contribute to improve this article, then share with us. We will include that code here.

 

Happy Coding !!
Happy Learning !!

Count and print number of repeated word occurrences in a String in Java