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:

Apache Commons Collections Bag
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
ETL with Spring Cloud Data Flow
Mảng (Array) trong Java
Java Program to Implement Network Flow Problem
Các kiểu dữ liệu trong java
Java Program to Implement Hash Tables chaining with Singly Linked Lists
What is a POJO Class?
Spring Boot - Creating Docker Image
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Exception Handling in Java
Java Program to Generate Random Numbers Using Probability Distribution Function
Java Program to Find the Minimum value of Binary Search Tree
Instance Profile Credentials using Spring Cloud
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
RegEx for matching Date Pattern in Java
Java Program to Check whether Directed Graph is Connected using DFS
Custom Error Pages with Spring MVC
Converting Java Date to OffsetDateTime
Java Program to Implement Treap
Fixing 401s with CORS Preflights and Spring Security
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Validations for Enum Types
Java Program to Implement Fermat Factorization Algorithm
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Comparing Two HashMaps in Java
Hướng dẫn Java Design Pattern – Composite
Cài đặt và sử dụng Swagger UI
LinkedHashSet trong java
Java Program to Delete a Particular Node in a Tree Without Using Recursion