Skip to content
Java project #15Intermediate

Text File Analyzer

Analyse one or more text files from the command line: counts, reading time, top words, word-length distribution, longest sentence and keyword search.

Estimated time
~4 hours to build
Files
6 files · 254 lines
Technologies
Java 21, java.nio.file, Regular expressions, Streams / Collectors

Introduction

Command-line tools such as wc and grep read files named as arguments, process them line by line and print a summary. This project builds a richer version in Java, practising java.nio.file, careful exception handling for missing or non-text files, and the Streams API.

Problem statement

Take one or more file names as command-line arguments, optionally followed by --find WORD. For each file report the number of lines (and blank lines), words, unique words, characters and letters; the number of sentences, average words per sentence and reading time at 200 words per minute; the five most frequent non-stop words; the distribution of word lengths; the longest sentence; and, with --find, every line containing the keyword with its line number. Report missing or unreadable files without stopping.

Objectives

  • Process command-line arguments
  • Read files with Files.readAllLines and handle specific IOExceptions
  • Tokenise text with regular expressions
  • Summarise data with groupingBy and sorted streams

Features

  • Several files per run
  • Word, sentence and character statistics
  • Top words and length histogram
  • Keyword search with line numbers
  • Graceful handling of missing and non-UTF-8 files

Concepts demonstrated

  • Command-line arguments
  • Specific exception handling
  • Tokenisation
  • Frequency analysis
  • Text processing

System architecture

main separates file names from the optional --find WORD and calls analyse for each file, catching NoSuchFileException, MalformedInputException and other IOExceptions separately. analyse reads the lines, splits the lower-cased text on non-word characters into words, splits sentences with a look-behind regex on ., ! or ?, and computes statistics with streams: frequency via groupingBy(identity, counting()), lengths via a TreeMap, and the longest sentence via max.

Folder structure

TextProject tree
text-file-analyzer/
├── README.md
├── data/haiku.txt
├── data/java-history.txt
├── src/Main.java
├── tests/args.txt
└── tests/expected-output.txt

Complete source code

src/Main.java

88 lines
Javasrc/Main.java
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Text File Analyzer — reads one or more text files named on the command line and reports
* line/word/character counts, reading time, the most frequent words, word-length distribution,
* the longest sentence and a keyword search, using java.nio.file and the Streams API.
*
* Usage: java -cp out Main FILE... [--find WORD]
*/
public class Main {
static final Set<String> STOP = Set.of("a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "in", "is", "it", "its", "of", "on", "or", "that", "the", "this", "to", "was", "with");
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java -cp out Main FILE... [--find WORD]");
return;
}
int findAt = Arrays.asList(args).indexOf("--find");
String keyword = findAt >= 0 && findAt + 1 < args.length ? args[findAt + 1].toLowerCase() : null;
List<String> files = Arrays.stream(args).limit(findAt >= 0 ? findAt : args.length).toList();
for (String name : files) {
System.out.println("==== " + name + " ====");
try {
analyse(Path.of(name), keyword);
} catch (NoSuchFileException e) {
System.out.println("File not found: " + name);
} catch (MalformedInputException e) {
System.out.println("Not a UTF-8 text file: " + name);
} catch (IOException e) {
System.out.println("Cannot read " + name + ": " + e.getMessage());
}
System.out.println();
}
}
static void analyse(Path file, String keyword) throws IOException {
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
String text = String.join("\n", lines);
List<String> words = Arrays.stream(text.toLowerCase().split("[^a-z0-9']+"))
.map(w -> w.replaceAll("^'+|'+$", "")).filter(w -> !w.isEmpty()).toList();
long blank = lines.stream().filter(String::isBlank).count();
long chars = text.chars().filter(c -> c != '\n').count();
long letters = text.chars().filter(Character::isLetter).count();
List<String> sentences = Arrays.stream(text.replace('\n', ' ').split("(?<=[.!?])\\s+")).map(String::trim).filter(s -> !s.isEmpty()).toList();
System.out.printf("Lines %d (%d blank), words %d, unique %d, characters %d (letters %d)%n", lines.size(), blank, words.size(), new java.util.HashSet<>(words).size(), chars, letters);
System.out.printf("Sentences %d, average %.1f words per sentence, reading time ~%d min%n", sentences.size(), (double) words.size() / Math.max(1, sentences.size()), Math.max(1, Math.round(words.size() / 200.0)));
Map<String, Long> freq = words.stream().filter(w -> !STOP.contains(w)).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("Top words:");
freq.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(5)
.forEach(e -> System.out.printf(" %-12s %3d %s%n", e.getKey(), e.getValue(), "*".repeat(e.getValue().intValue())));
Map<Integer, Long> lengths = words.stream().collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
System.out.println("Word lengths: " + lengths.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue()).collect(Collectors.joining(" ")));
sentences.stream().max(Comparator.comparingInt((String s) -> s.split("\\s+").length))
.ifPresent(s -> System.out.println("Longest sentence (" + s.split("\\s+").length + " words): " + (s.length() > 70 ? s.substring(0, 67) + "..." : s)));
if (keyword != null) {
System.out.println("Lines containing '" + keyword + "':");
String k = keyword;
int[] n = {0};
Stream.iterate(0, i -> i + 1).limit(lines.size())
.filter(i -> lines.get(i).toLowerCase().contains(k))
.forEach(i -> { n[0]++; System.out.printf(" %3d: %s%n", i + 1, lines.get(i).trim()); });
if (n[0] == 0) System.out.println(" (none)");
}
}
}

What each file does

src/Main.java
Argument handling, per-file exception handling, and the statistics in analyse.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main data/java-history.txt data/haiku.txt --find java

Test against the expected output

Terminal
java -cp out Main $(cat tests/args.txt) > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# java -cp out Main data/java-history.txt data/haiku.txt data/missing.txt --find java > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
==== data/java-history.txt ====
Lines 8 (2 blank), words 81, unique 60, characters 484 (letters 389)
Sentences 7, average 11.6 words per sentence, reading time ~1 min
Top words:
java 6 ******
because 2 **
bytecode 2 **
machine 2 **
runs 2 **
Word lengths: 1:1 2:8 3:19 4:16 5:8 6:4 7:13 8:9 10:2 12:1
Longest sentence (15 words): Java programs are compiled to bytecode, and the bytecode runs on th...
Lines containing 'java':
1: Java was created by James Gosling and his team at Sun Microsystems.
4: Java programs are compiled to bytecode, and the bytecode runs on the Java Virtual Machine.
6: Today Java powers banking systems, Android apps and large web services.
8: Is Java still worth learning? Most developers would say yes, because Java is fast, stable and widely used.
==== data/haiku.txt ====
Lines 3 (0 blank), words 13, unique 12, characters 68 (letters 54)
Sentences 4, average 3.3 words per sentence, reading time ~1 min
Top words:
pond 2 **
again 1 *
frog 1 *
into 1 *
jumps 1 *
Word lengths: 1:1 2:1 3:2 4:4 5:2 6:2 7:1
Longest sentence (6 words): A frog jumps into the pond.
Lines containing 'java':
(none)
==== data/missing.txt ====
File not found: data/missing.txt

Testing

  • The test passes the arguments in tests/args.txt; compare the output with tests/expected-output.txt.
  • java is the most frequent word (6 times) in java-history.txt; the haiku has no matching lines.
  • data/missing.txt is reported as 'File not found' and the program continues.

Common errors

MalformedInputException on some files

The file isn't valid UTF-8; catch the exception or read with the file's real charset.

"don't" is split into don and t

Include the apostrophe in the word pattern ([^a-z0-9']+) and trim apostrophes at the ends.

Possible improvements

  • Accept a directory and analyse every .txt file in it
  • Detect the language from stop-word frequencies
  • Output the report as JSON with a --json flag

Additional challenges

  1. 1Compute the Flesch reading-ease score.
  2. 2Find the most common two-word phrases.
  3. 3Highlight the keyword inside matching lines.

Built and tested it yourself? Mark it to update your dashboard.