Java Programs›File Handling›Count Lines, Words and Characters in a File

Count Lines, Words and Characters in a File in Java

intermediate·  File Handling  ·  File I/O

Problem

A word counter treats any run of whitespace as a single separator, so extra spaces and blank lines don't create empty words.

Given a text file, report how many lines, words and characters (excluding line breaks) it contains.

Input
story.txt with 4 lines
Output
Lines: 4, Words: 13, Characters: 58

Java Program

Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; public class CountLinesWordsChars { public static void main(String[] args) throws IOException { Path file = Paths.get("story.txt"); Files.write(file, Arrays.asList("Once upon a time", " there was a tiny robot", "", "It liked to count")); int lines = 0, words = 0, chars = 0; try (BufferedReader reader = new BufferedReader(new FileReader(file.toFile()))) { String line; while ((line = reader.readLine()) != null) { lines++; chars += line.length(); // characters on the line, not counting the line break String trimmed = line.trim(); if (!trimmed.isEmpty()) { words += trimmed.split("\\s+").length; // runs of spaces count as one separator } } } System.out.println("Lines: " + lines); System.out.println("Words: " + words); System.out.println("Characters: " + chars); Files.delete(file); } }

Output

Lines: 4 Words: 13 Characters: 58

Core Logic

Reading line by line, each line updates three counters: one line, its length in characters, and the number of words found after trimming.

How It Works
  1. 1The program writes a sample file that includes a blank line and doubled spaces.
  2. 2lines increments once per readLine() call.
  3. 3chars += line.length() counts characters, excluding the line break.
  4. 4Blank lines are skipped for words; others are trimmed and split on \\s+.
The line " there was a tiny robot" trims to five words even though it has leading and doubled spaces.
💡

Key Point: Calling "".split("\\s+") returns an array of length 1, not 0 — that's why blank lines need the isEmpty() check.

Complexity
Time Complexity: O(n)Space Complexity: O(L)

Why: Each character is read once, and only one line of length L is in memory at a time.

Key Concepts

BufferedReadertrim()split("\\s+")counters

Approach 2: Using Streams

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class CountLinesWordsCharsStream { public static void main(String[] args) throws IOException { Path file = Paths.get("story.txt"); Files.write(file, Arrays.asList("Once upon a time", " there was a tiny robot", "", "It liked to count")); List<String> all = Files.readAllLines(file); long words = all.stream() .map(String::trim) .filter(line -> !line.isEmpty()) .mapToLong(line -> line.split("\\s+").length) .sum(); int chars = all.stream().mapToInt(String::length).sum(); System.out.println("Lines: " + all.size() + ", Words: " + words + ", Characters: " + chars); Files.delete(file); } }

Output

Lines: 4, Words: 13, Characters: 58

Core Logic

For files that fit in memory, reading all lines into a list lets streams compute each count declaratively.

How It Works
  1. 1Files.readAllLines loads every line into a List.
  2. 2all.size() is the line count.
  3. 3A stream trims lines, drops empty ones, maps each to its word count and sums them.
  4. 4mapToInt(String::length).sum() totals the characters.
The blank third line contributes 1 to the line count but 0 to words and characters.
💡

Key Point: readAllLines holds the whole file in memory — fine for small files, but stick to line-by-line reading for large logs.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: The whole file is loaded once, then streamed twice.

Key Concepts

Files.readAllLines()mapToLong()mapToInt()

Interview Questions

How do you count lines quickly in a huge file?

Files.lines(path).count() streams the file without holding it in memory, which is much better than readAllLines for large files.

Should the newline characters be counted?

It depends on the definition. Tools like wc -c count bytes including newlines, while this program counts only the characters on each line.

Learn the Concept

Related Programs