How To Read A File from JUnit Test

To read the file: src/test/resources/test.file in a unit/integration test, the method Path.of is useful to set the working directory:

import java.nio.file.Files;
import java.nio.file.Path;
import static;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before;
import org.junit.Test;    

public class ReadFileTest {

    private Path workingDir;

    public void init() {
        this.workingDir = Path.of("", "src/test/resources");

    public void read() throws IOException {
        Path file = this.workingDir.resolve("test.file");
        String content = Files.readString(file);
        assertThat(content, is("duke"));


The method Files.readString ships with Java 11+.

Path.of should be preferred over Paths.get. Thanks to @sormuras for the hint


Too many lines of code for such a simple thing.

Posted by Simplifier on April 14, 2020 at 09:18 PM CEST #

"It is recommended to obtain a Path via the Path.of methods instead of via the get methods defined in this class as this class may be deprecated in a future release."


Posted by Christian Stein on April 15, 2020 at 09:45 AM CEST #

An option without hardcoding src/test/resources:

try (InputStream inputStream = ReadResourceTest.class.getResourceAsStream("test.file")) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String content = bos.toString(UTF_8);
assertThat(content, is("duke"));

With help from here:

Posted by Arend v. Reinersdorff on April 18, 2020 at 03:49 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments