Explain Codes LogoExplain Codes Logo

How to read a text-file resource into Java unit test?

java
input-stream
file-reading
java-8
Nikita BarsukovbyNikita Barsukov·Feb 20, 2025
TLDR
String fileName = "example.txt"; // Tip: replace "/" with "\\" if you're a Windows user who's fed up with traditions 😆 InputStream is = this.getClass().getResourceAsStream("/" + fileName); // Because nobody wants to lose their line breaks, do they? String content = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)) .lines().collect(Collectors.joining(System.lineSeparator()));

Make sure you've stored the example.txt in the src/test/resources directory if you're using Maven or something similar for Gradle.

Essential InputStream to String Conversion

When we need a String out of our resource, we can convert an InputStream into a String like this:

String result = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .lines().collect(Collectors.joining("\n"));

This uses Java 8's streams. Make sure to specify character encoding (UTF-8 is typically a safe bet).

Libraries That Do the Heavy Lifting

Thank goodness for libraries like Apache Commons IO and Google Guava. They can make file operations a breeze.

String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); // Courtesy of Apache Commons IO. Thanks, Apache!

When Size Does Matter: Dealing with Large Files

Working with large files? Let's avoid a game of OutOfMemoryError whack-a-mole. You can read the file line by line or with streams. Be ready to handle cases when the file can't be found or is inaccessible.

The Future is Now: Java NIO

For Java 7 and onwards, the java.nio.file.Files class offers methods for reading a file:

List<String> lines = Files.readAllLines(Paths.get(resource.toURI()), StandardCharsets.UTF_8); String content = String.join("\n", lines); // Wall of text, meet your nemesis: line breaks!

Architect the Robustness

Don't forget to handle potential errors and exceptions that might occur during file reading.

// Nobody's perfect; we need to plan for exceptions too catch(IOException ex) { throw new UncheckedIOException("Resource reading went wrong", ex); }

Clean Kitchen Philosophy: Close Your Resources

Prevent resource leakage by closing your resources. InputStream is auto-closable, so it makes it easier. Here's how:

try(InputStream is = this.getClass().getResourceAsStream("/example.txt")) { // Resource handling code here... } // Look, ma! No leaks!