Java Read Classpath Resource as String using Apache Commons IO

Tags: Classpath Resource String IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to read a classpath resource into a String using the IOUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

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

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Read Classpath resource as String

For example, we have a file in classpath at src/main/resources/test.txt with the content as below.

Simple Solution
Java Tutorials
Apache Commons IO Tutorials

The Java program below, we use the IOUtils.resourceToByteArray() method to read the file content into a String.

ReadResourceToString.java

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ReadResourceToString {
    public static void main(String... args) {
        try {
            String resourceContent = IOUtils.resourceToString("/test.txt", StandardCharsets.UTF_8);

            System.out.print(resourceContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Simple Solution
Java Tutorials
Apache Commons IO Tutorials

Happy Coding 😊