Practice File I/O in Java

Read from and write to files using Java I/O streams and utilities.

Work through 24 exercises with starter code, expected output, test cases, and hints.

How to learn File I/O

Java file I/O connects program data to an external resource whose existence, encoding, permissions, and lifetime are outside the program’s control. Good file code therefore makes the character encoding explicit, closes resources reliably, and decides what should happen for missing or malformed input.

Prefer the modern java.nio.file Path and Files APIs for common tasks. They compose paths without manual separators and offer concise operations for strings, lines, copying, existence checks, and buffered streams. Use streaming reads when a file may be too large to hold in memory.

Recommended learning order

  1. Paths and small files: Create Path values and read or write small UTF-8 content with Files. Distinguish a path description from an existing file.
  2. Reliable resource handling: Use try-with-resources for readers, writers, and streams; understand when a convenience Files method already manages the resource.
  3. Stream large inputs: Read line by line or through a buffered stream instead of loading unbounded data all at once.
  4. Preserve and replace data safely: Choose append versus truncate deliberately, handle atomic replacement where needed, and avoid writing over the input before a transformation succeeds.

Tested example: Write and read UTF-8 text

A temporary file keeps the example self-contained. Files.writeString and readString use the stated encoding, and the finally block removes this demo file after the read completes.

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("java-lab-", ".txt");
        try {
            Files.writeString(file, "alpha\nbeta\n", StandardCharsets.UTF_8);
            long lines = Files.readAllLines(file, StandardCharsets.UTF_8).size();
            System.out.println("Lines: " + lines);
        } finally {
            Files.deleteIfExists(file);
        }
    }
}

Expected output

Lines: 2

Change and run this example in the Java compiler

Common mistakes

  • Relying on the platform default encoding, which can produce different text on another machine.
  • Opening a writer in truncate mode when the intention was to append, silently replacing existing content.
  • Reading an arbitrarily large file into one String or List and exhausting memory.
  • Building paths by concatenating slash characters instead of using Path.resolve or Paths.get.

How to practice

Begin with writing and reading a small known file, then append, copy, count lines, and stream larger content. Browser compiler environments can restrict filesystem behavior, so treat the examples as Java API practice and never submit private file contents to the online compiler.

Exercises to do first

  • Write to a file — Choose an encoding and make replacement behavior explicit.
  • Read from a file — Handle the missing-file case and close any opened resource.
  • Copy a file — Preserve the source and decide how an existing destination is handled.

File I/O exercises

  1. Write to File Java exercise — Write text to a file
  2. Read from File Java exercise — Read contents of a file
  3. Append to File Java exercise — Append text to existing file
  4. Count Lines in File Java exercise — Count the number of lines in a file
  5. Copy File Java exercise — Copy contents from one file to another
  6. Check File Exists Java exercise — Check if a file exists before operations
  7. Count Words in File Java exercise — Count total words in a file
  8. Search in File Java exercise — Search for a word in file and count occurrences
  9. Reverse File Lines Java exercise — Reverse the order of lines in a file
  10. Merge Multiple Files Java exercise — Merge contents of multiple files
  11. Remove Duplicate Lines Java exercise — Remove duplicate lines from a file
  12. Sort File Lines Java exercise — Sort lines of a file alphabetically
  13. File Statistics Java exercise — Calculate statistics about a text file
  14. Simple CSV Reader Java exercise — Parse a simple CSV file
  15. Find and Replace in File Java exercise — Find and replace text in a file
  16. Log File Parser Java exercise — Parse and filter log entries
  17. Word Frequency Counter Java exercise — Count word frequencies in a file
  18. Simple File Encryption Java exercise — Encrypt file contents using Caesar cipher
  19. Config File Parser Java exercise — Parse a key=value configuration file
  20. File Difference Checker Java exercise — Compare two files and show differences
  21. Simple JSON Handler Java exercise — Read and parse simple JSON from file
  22. CSV Parser Java exercise — Parse CSV formatted data
  23. Extract Error Entries from Logs Java exercise — Extract errors from log entries
  24. Configuration Reader Java exercise — Parse key=value configuration format

Browse the complete Java practice path · Open the online Java compiler