Java Programs›File Handling›Search for a Word in a File

Search for a Word in a File in Java

beginner·  File Handling  ·  File I/O

Problem

Searching a file line by line keeps memory use small, and line numbers make each match easy to find in the original file.

Find every line in a server log that contains the word ERROR, printing its line number and text.

Input
a 5-line log with 2 ERROR lines
Output
Line 3 and Line 5

Java Program

Java
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class SearchWordInFile { public static void main(String[] args) throws IOException { Path file = Paths.get("server.log"); Files.writeString(file, "10:00 INFO started\n10:02 WARN slow disk\n10:05 ERROR timeout\n10:07 INFO ok\n10:09 ERROR retry failed\n"); String word = "ERROR"; int lineNo = 0, matches = 0; try (BufferedReader reader = Files.newBufferedReader(file)) { String line; while ((line = reader.readLine()) != null) { lineNo++; if (line.contains(word)) { // case-sensitive substring match matches++; System.out.println("Line " + lineNo + ": " + line); } } } System.out.println(matches + " lines contain \"" + word + "\""); Files.delete(file); } }

Output

Line 3: 10:05 ERROR timeout Line 5: 10:09 ERROR retry failed 2 lines contain "ERROR"

Core Logic

Reading one line at a time, a counter tracks the line number and contains tests each line for the word.

How It Works
  1. 1The program writes a sample server.log first.
  2. 2A BufferedReader reads it in a while loop, incrementing lineNo.
  3. 3line.contains(word) checks each line; matches are counted and printed.
  4. 4A summary line reports the total.
Lines 3 and 5 contain ERROR, so the summary says 2 lines.
💡

Key Point: contains is case-sensitive and matches inside longer words — "ERRORS" would also match.

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

Why: Every character is read once, and only one line is held at a time.

Key Concepts

BufferedReadercontains()line counter

Approach 2: Whole-Word, Case-Insensitive Search

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SearchWordInFileRegex { public static void main(String[] args) throws IOException { Path file = Paths.get("notes.txt"); Files.writeString(file, "Java is fun.\nJavaScript is different.\nI drink java every morning.\n"); Pattern whole = Pattern.compile("\\bjava\\b", Pattern.CASE_INSENSITIVE); // whole word, any case int count = 0; for (String line : Files.readAllLines(file)) { Matcher m = whole.matcher(line); while (m.find()) count++; } System.out.println("Whole-word matches for \"java\": " + count); Files.delete(file); } }

Output

Whole-word matches for "java": 2

Core Logic

A regular expression with word boundaries finds whole words only, in any letter case.

How It Works
  1. 1\\bjava\\b matches "java" only where it isn't part of a longer word.
  2. 2CASE_INSENSITIVE also matches "Java".
  3. 3while (m.find()) counts every match on each line, not just the first.
"Java" and "java" match, but "JavaScript" doesn't, giving 2 matches.
💡

Key Point: Compile the Pattern once outside the loop; compiling a regex for every line is wasted work.

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

Why: readAllLines holds the file in memory, then each character is scanned once.

Key Concepts

Pattern\\b word boundaryCASE_INSENSITIVEMatcher.find()

Interview Questions

How would you search a very large file quickly?

Stream it line by line with Files.lines and filter, which keeps memory low; for repeated searches, build an index instead of rescanning.

How do you search every file in a folder?

Walk the folder with Files.walk, filter regular files (and maybe by extension), and run the same line search on each.

Learn the Concept

Related Programs