Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java file exercises: UTF-8 round trips, missing files and cleanup

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A file round-trip exercise verifies decoded content, failure behavior and owned-file cleanup as separate outcomes.

Java 8+. This is a complete program using JDK classes.

Check values rather than a success message

Write two titles as UTF-8, read them back using the same charset and compare the complete ordered result. Merely checking that a file exists can pass after writing the wrong content or an empty file.

The second case attempts to read a missing file and must fail. The third removes the written file and verifies absence. The exercise owns its temporary directory, so cleanup cannot accidentally delete a user’s unrelated working files.

Files.readAllLines is reasonable for these two short fixture records, but it materializes the input. A large import needs a streaming parser with byte, line and record-count budgets. Encoding, record grammar and I/O failure are separate validation layers.

Working program

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class FileRoundTripExercises {
    public static void main(String[] args) throws Exception {
        Path directory=Files.createTempDirectory("aitrove-file-check-");Path file=directory.resolve("titles.txt");
        try{
            List<String> expected=Arrays.asList("Caf\u00e9 notes","Parcel handbook");
            Files.write(file,expected,StandardCharsets.UTF_8);
            if(!Files.readAllLines(file,StandardCharsets.UTF_8).equals(expected))throw new AssertionError("Round trip changed");
            try{Files.readAllLines(directory.resolve("missing.txt"),StandardCharsets.UTF_8);throw new AssertionError("Missing file accepted");}
            catch(IOException rejected){ }
            Files.delete(file);if(Files.exists(file))throw new AssertionError("File retained");
            System.out.println("3 file checks passed");
        }finally{Files.deleteIfExists(file);Files.deleteIfExists(directory);}
    }
}

Output

Output
3 file checks passed

Costs and boundaries

The round trip visits the encoded bytes and keeps the decoded lines in memory. Its test data is fixed and small. This is not a crash-recovery, concurrent-writer or permission-boundary test; those scenarios require separate fixtures and explicit ownership decisions.

Common Mistakes

  • File existence is not content equality.
  • Use the intended charset on both boundaries.
  • Do not clean a directory the test does not exclusively own.

Read next

File resource boundaries, Persisted membership.

java
file-exercises
Storage details