Read Content from URI into String in Java using Apache Commons IO

Tags: URI String IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to get the content of an URI into a String object using IOUtils utility 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 get content of URI as a String using IOUtils class

For example, we have a text file at D:\Data\data.txt with content as below.

Simple Solution
Java Tutorials
Apache Commons IO Tutorials
Spring Boot Tutorials

In the following Java program we use the IOUtils.toString() method with a given URI object to read the content of URI as a String.

URIToString.java

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class URIToString {
    public static void main(String... args) {
        try {
            URI uri = new URI("file:/D:/Data/data.txt");

            String data = IOUtils.toString(uri, StandardCharsets.UTF_8);

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

Happy Coding 😊