Count total number of Characters, Words and Lines

Recently I got an email asking for “Can I have a tutorial on counting total number of words, lines and characters from file?”

Some time back I’ve written an article on How to Read a File Line by Line in Reverse Order which doesn’t print above requested metrics. In this tutorial we will go over steps on how to print total number of Characters, Words and Lines for a given file.

Let’s get started:

  1. We will read file crunchify.txt first located at /Users/appshah/Downloads/ folder. I’m running program on my Macbook Pro so replace username from appshah with your actual name.
  2. We will read each line and will remove multiple whitespace using regex \\s
  3. Print file and results on console

If you need more information on REGEX pattern in java then follow below tutorials:

NOTE:  We are using try-with-resources statement

try (BufferedReader crunchifyBuffer = new BufferedReader(new FileReader(crunchifyFile))) {
        // perform task, i.e. readline. BufferedReader will be closed automatically after try block :)
} catch (Exception e){
       // Log exception
}

File we are using:

<?php

// Silence is golden.
This is Crunchify's tutorial which counts total number of char, words and lines...

?>

Java code:

package crunchify.com.tutorials;

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

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyCountWordsLineCharacters {

        public static void readFileAndPrintCounts(String crunchifyFile) throws FileNotFoundException {

                int crunchifyTotalWords = 0;
                int crunchifyTotalLines = 0;
                int crunchifyTotalCharacters = 0;

                String crunchifyLine;

                // Read file contents
                // The try-with-resources statement is a try statement that declares one or more resources. A resource is an
                // object that must be closed after the program is finished with it. The try-with-resources statement ensures
                // that each resource is closed at the end of the statement.
                try (BufferedReader crunchifyBuffer = new BufferedReader(new FileReader(crunchifyFile))) {
                        crunchifyLog("========== File Content ==========");

                        // read each line one by one
                        while ((crunchifyLine = crunchifyBuffer.readLine()) != null) {
                                crunchifyLog(crunchifyLine);
                                crunchifyTotalLines++;

                                // ignore multiple white spaces
                                String[] myWords = crunchifyLine.replaceAll("\\s+", " ").split(" ");

                                for (String s : myWords) {
                                        crunchifyTotalCharacters += s.length();
                                }

                                crunchifyTotalWords += myWords.length;

                        }
                } catch (IOException e) {
                        e.printStackTrace();
                }
                crunchifyLog("\n========== Result ==========");

                crunchifyLog("* Total Characters: " + crunchifyTotalCharacters);
                crunchifyLog("* Total Words: " + crunchifyTotalWords);
                crunchifyLog("* Toal Lines: " + crunchifyTotalLines);
        }

        private static void crunchifyLog(String string) {
                System.out.println(string);
        }

        public static void main(String[] args) {
                try {
                        String crunchifyFile = "/Users/appshah/Downloads/crunchify.txt";
                        readFileAndPrintCounts(crunchifyFile);
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                }
        }
}

Console Output:

========== File Content ==========
<?php

// Silence is golden.
This is Crunchify's tutorial which counts total number of char, words and lines...

?>

========== Result ==========
* Total Characters: 95
* Total Words: 21
* Total Lines: 6

The post How to read File in Java and Count total number of Characters, Words and Lines appeared first on Crunchify.