Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

1. Overview

In this quick tutorial we’re going to illustrate how to convert a simple byte[] to an InputStream, first using plain java and then the Guava library.

This article is part of the “Java – Back to Basic” series here on Baeldung.

2. Convert using Java

First – let’s look at the Java solution:

@Test
public void givenUsingPlainJava_whenConvertingByteArrayToInputStream_thenCorrect() 
  throws IOException {
    byte[] initialArray = { 0, 1, 2 };
    InputStream targetStream = new ByteArrayInputStream(initialArray);
}

3. Convert using Guava

Next – let’s use wrap the byte array into the Guava ByteSource – which then allows us to get the stream:

@Test
public void givenUsingGuava_whenConvertingByteArrayToInputStream_thenCorrect() 
  throws IOException {
    byte[] initialArray = { 0, 1, 2 };
    InputStream targetStream = ByteSource.wrap(initialArray).openStream();
}

And there you have it – a simple way of opening an InputStream from a byte array.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE