Java
Unit Testing
File Handling
Resource Management
Coding Tutorials

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Java unit tests, the usual place for sample files is src/test/resources. Once the file is on the test classpath, the most reliable way to read it is through getResourceAsStream(...) rather than hard-coding a filesystem path.

That distinction matters because tests may run from an IDE, Maven, Gradle, or a packaged classpath layout. Classpath loading keeps the test portable across those environments.

Put the File in src/test/resources

Suppose you have this file:

text
src/test/resources/sample/data.txt

At test runtime, that resource is available on the classpath.

The simplest pattern is:

java
1import static org.junit.jupiter.api.Assertions.assertTrue;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.nio.charset.StandardCharsets;
6
7import org.junit.jupiter.api.Test;
8
9class ResourceTest {
10    @Test
11    void readsResource() throws IOException {
12        try (InputStream in = getClass().getResourceAsStream("/sample/data.txt")) {
13            String text = new String(in.readAllBytes(), StandardCharsets.UTF_8);
14            assertTrue(text.contains("expected text"));
15        }
16    }
17}

The leading / means the path is resolved from the classpath root.

Why getResourceAsStream Is Better Than a Raw File Path

This is tempting:

java
Path path = Path.of("src/test/resources/sample/data.txt");

It may work locally, but it ties the test to a particular working directory and filesystem layout.

Classpath loading is more robust because it asks the class loader for the resource exactly the way the test runtime sees it.

That makes the test less fragile when run from different tools.

Read the Resource as Text Cleanly

If you prefer buffered reading:

java
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStreamReader;
4import java.nio.charset.StandardCharsets;
5import java.util.stream.Collectors;
6
7String text;
8try (BufferedReader reader = new BufferedReader(
9        new InputStreamReader(
10            getClass().getResourceAsStream("/sample/data.txt"),
11            StandardCharsets.UTF_8))) {
12    text = reader.lines().collect(Collectors.joining("
13"));
14}

This is useful when you want line-oriented control or explicit text handling.

Fail Fast If the Resource Is Missing

A missing resource should usually fail the test immediately and clearly.

java
1import static org.junit.jupiter.api.Assertions.assertNotNull;
2
3InputStream in = getClass().getResourceAsStream("/sample/data.txt");
4assertNotNull(in, "resource not found");

That gives a much better failure message than a later NullPointerException.

If You Really Need a Path

Sometimes an API specifically wants a Path. If the resource is actually available as a regular file on disk, you can convert the resource URL to a URI.

java
1import java.net.URISyntaxException;
2import java.nio.file.Files;
3import java.nio.file.Path;
4
5Path path = Path.of(getClass().getResource("/sample/data.txt").toURI());
6String text = Files.readString(path);

But be careful with this pattern. It assumes the resource can be represented as a normal filesystem path. getResourceAsStream is still the safer general default.

JUnit and Test Utility Helpers

If many tests load resources the same way, extract the boilerplate into a helper method so every test uses the same classpath-safe pattern.

java
1static String readResource(String path) throws IOException {
2    try (InputStream in = ResourceTest.class.getResourceAsStream(path)) {
3        if (in == null) {
4            throw new IllegalArgumentException("Missing resource: " + path);
5        }
6        return new String(in.readAllBytes(), StandardCharsets.UTF_8);
7    }
8}

This keeps the test bodies short and makes resource-loading failures easier to diagnose consistently across the test suite.

Common Pitfalls

The biggest mistake is reading src/test/resources/... through a hard-coded relative path and assuming every test runner will share the same working directory.

Another common issue is forgetting the leading / when using getResourceAsStream, which changes how the path is resolved.

People also skip the null check and then waste time debugging a NullPointerException instead of a clean "resource not found" test failure.

Finally, if all you need is the file contents, do not force the resource into a Path. Streams are usually simpler and more portable.

Summary

  • Put test files in src/test/resources.
  • Use getResourceAsStream(...) for the most portable loading behavior.
  • Read the bytes or wrap the stream in a reader for text.
  • Assert that the resource exists before using it.
  • Use filesystem Path conversion only when an API truly requires it.
  • Avoid hard-coded source-tree file paths in unit tests.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.