Java Byte Array to InputStream

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 VietMX’s Blog.

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.

Related posts:

Guide to ThreadLocalRandom in Java
Java Program to Implement the Bin Packing Algorithm
Cơ chế Upcasting và Downcasting trong java
Working With Maps Using Streams
Java Program to implement Array Deque
Java Program for Topological Sorting in Graphs
Java Program to Find the Longest Path in a DAG
Hướng dẫn Java Design Pattern – Dependency Injection
Converting String to Stream of chars
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Adding a Newline Character to a String in Java
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Java Program to Implement Flood Fill Algorithm
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Spring Boot - Enabling Swagger2
Java Program to Implement Stack API
Predicate trong Java 8
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Debug a JavaMail Program
Converting Between a List and a Set in Java
Java Program to Solve the Fractional Knapsack Problem
Java Program to Implement Floyd Cycle Algorithm
Spring REST API with Protocol Buffers
Java Program to Construct an Expression Tree for an Infix Expression
Java Program to Implement Adjacency Matrix
Instance Profile Credentials using Spring Cloud
Convert char to String in Java
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
A Guide to System.exit()
Merging Two Maps with Java 8
Converting String to Stream of chars
Java Program to Implement Coppersmith Freivald’s Algorithm