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:

Abstract class và Interface trong Java
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Jackson – Unmarshall to Collection/Array
Concurrent Test Execution in Spring 5
Hướng dẫn Java Design Pattern – Chain of Responsibility
Guide to Mustache with Spring Boot
Java Program to Implement Floyd Cycle Algorithm
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Spring 5 and Servlet 4 – The PushBuilder
Java Program to Search for an Element in a Binary Search Tree
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Check Cycle in a Graph using Graph traversal
Guide to @ConfigurationProperties in Spring Boot
Quick Guide to java.lang.System
Split a String in Java
Java Optional as Return Type
Java Program to Implement Red Black Tree
Java Program to Implement Sorted Circular Doubly Linked List
Vòng lặp for, while, do-while trong Java
Các nguyên lý thiết kế hướng đối tượng – SOLID
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Perform Searching Based on Locality of Reference
Java Program to Construct an Expression Tree for an Prefix Expression
Spring Boot Configuration with Jasypt
Java Program to Implement Shoelace Algorithm
Java Program to Generate Random Hexadecimal Byte
Một số ký tự đặc biệt trong Java
Từ khóa this và super trong Java
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Posting with HttpClient
JWT – Token-based Authentication trong Jersey 2.x
Merging Two Maps with Java 8