Find and Replace in File in Java: Explanation & Practice

Find and replace text in a file

Problem summary

Replace all occurrences of a word in a file with another word.

Starter code

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String find = "old";
        String replace = "new"; // Test case 1
        
        // Replace all occurrences
        // Print: Replaced <count> occurrences
    }
}

Expected output and test cases

  • 5 replacements made
    Replaced 5 occurrences
  • Word not found
    Replaced 0 occurrences
  • Many replacements
    Replaced 10 occurrences

Hints

  1. Read entire file content
  2. Use String.replace() or replaceAll()
  3. Count occurrences before replacing

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler