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.
