Table of Contents
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:
Spring Cloud AWS – Messaging Support
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Spring Boot - OAuth2 with JWT
Overflow and Underflow in Java
Hướng dẫn Java Design Pattern – Composite
Java Program to Solve Knapsack Problem Using Dynamic Programming
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Guide to java.util.concurrent.Locks
Spring Data MongoDB Transactions
Posting with HttpClient
The DAO with Spring and Hibernate
Introduction to Spring Cloud CLI
Java List UnsupportedOperationException
Spring Data Reactive Repositories with MongoDB
Hướng dẫn Java Design Pattern – Service Locator
Testing an OAuth Secured API with Spring MVC
Java Program to Solve Tower of Hanoi Problem using Stacks
Spring Boot Annotations
Finding the Differences Between Two Lists in Java
Java Program to Implement Sieve Of Eratosthenes
Comparing Strings in Java
REST Web service: Basic Authentication trong Jersey 2.x
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Find the Connected Components of an UnDirected Graph
Spring Security Custom AuthenticationFailureHandler
Java Program to Implement Ternary Heap
Immutable ArrayList in Java
Spring Security Form Login
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Implement Find all Back Edges in a Graph
Java Program to Implement Stack using Two Queues
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x