Convert Byte Array to InputStream in Java

May 16, 2020 No comments Java IO Conversions Byte Array InputStream

1. Introduction

In this article, we are going to learn how to convert byte array to InputStream in Java using built-in methods and external libraries like Guava and Apache Commons IO.

For more Java I/O related articles, check the following links:

2. Byte array to InputStream with ByteArrayInputStream

Let's start with a simple solution that comes with plain Java:

package com.frontbackend.java.io.conversions.toinputstream.frombytearray;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class ByteArrayToInputStreamUsingByteArrayInputStream {

    public static void main(String[] args) {
        byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8);

        InputStream targetStream = new ByteArrayInputStream(bytes);
    }
}

In this example we use ByteArrayInputStream object to create an instance of the InputStream type.

3. Convert byte array to InputStream using Guava

When using Guava library, first we have to wrap byte array with ByteSource object that contains openStream() method which returns InputStream:

package com.frontbackend.java.io.conversions.toinputstream.frombytearray;

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

import com.google.common.io.ByteSource;

public class ByteArrayToInputStreamUsingGuava {

    public static void main(String[] args) throws IOException {
        byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8);

        InputStream targetStream = ByteSource.wrap(bytes)
                                             .openStream();
    }
}

4. Using Apache Commons IO to convert byte[] to InputStream

Apache Commons IO library also gives us a solution but not so straightforward:

package com.frontbackend.java.io.conversions.toinputstream.frombytearray;

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

import org.apache.commons.io.IOUtils;

public class ByteArrayToInputStreamUsingIOUtils {

    public static void main(String[] args) throws IOException {
        byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8);

        InputStream inputStream = IOUtils.toInputStream(new String(bytes), StandardCharsets.UTF_8);
    }
}

First, we have to create a String object from our byte array, then use IOUtils.toInputStream to convert it into InputStream. Note that converting from String to InputStream requires encoding.

5. Conclusion

In this short article, we showed ways to convert byte array to InputStream in Java. We presented several solutions but suggest using the simplest one with the plain Java. This one is a straightforward way to achieve that conversion.

Code examples used in this tutorial can be found under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}