Read Content from URL into Byte Array in Java using Apache Commons IO

Tags: URL Byte Array IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to get the content of an URL into a byte array 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 URL as a Byte Array using IOUtils class

In the following Java program we use the IOUtils.toByteArray() method with a given URL object to read the content of the URL as a byte array.

URLToByteArray.java

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URL;

public class URLToByteArray {
    public static void main(String... args) {
        try {
            URL url = new URL("https://simplesolution.dev");

            byte[] data = IOUtils.toByteArray(url);

            for(byte b: data) {
                System.out.print((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
<!DOCTYPE html>
<html><head>
....
</script></body>
</html>

Happy Coding 😊