Kotlin – Count words in File

Kotlin – Count words in File

To count the words in a file in Kotlin, you can read the file content, split the file content into words using String split() method, and then get the size of the words list using List size property.

Steps to count words in File

Follow these steps to find the number of words in the file, given by a file path.

  1. Import java.io.File class.
  2. Given file path in filePath variable.
  3. Create a File object using the file path filePath, and read its content using File.readText() to a variable say text.
  4. Split text into words using String split() method. Pass “one or more consecutive spaces” regular string for the split() method.
  5. Filter the non-empty words using List filter() method and then count them using the List size property.

Kotlin Program to Count Words in File

In this example program, we shall take a file 'example.txt', and count the words in it.

The original contents of the 'example.txt' is given below.

Kotlin - Count words in File - Input file
Original File content

Main.kt

import java.io.File

fun main() {
    val filePath = "example.txt" // Replace with the path to your file

    try {
        val file = File(filePath)

        if (file.exists() && file.isFile) {
            val text = file.readText()
            // Split the text into words using a regular expression
            val words = text.split(Regex("\\s+"))

            // Filter out empty strings and count the non-empty words
            val wordCount = words.filter { it.isNotBlank() }.size
            println("Word count : $wordCount")
        } else {
            println("File not found or is not a regular file.")
        }
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    }
}

Output

Word count : 15

There are 15 words in the given file, and the output reflects the same.

Summary

In this Kotlin File Operations tutorial, we have seen how to count the words in a file using String split() method, with a detailed step by step process, and example programs.