Very often I store test data for tests in .json files under the “resources” folder. When I need to get test data as objects I read the file to String and then convert to Java objects.

The simpliest way to a read file to a String is using IOUtils from Apache Commons IO.

Apache Commons IO Maven dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

IOUtils. Read file to String

That method reads the content of the file “fileName” and returns it as a string.

Another popular approach to read а file to String - Guava

Google Guava Maven dependency

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>

Guava. Read file to String

Github Gists related to “read file to String”:


You may also find these posts interesting: