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 Boot - Zuul Proxy Server and Routing
Java Program to Implement Word Wrap Problem
Java Program to Represent Graph Using 2D Arrays
Java Program to implement Sparse Vector
Java Program to Perform Searching in a 2-Dimension K-D Tree
Java Program to Check whether Graph is a Bipartite using DFS
The Guide to RestTemplate
Java Program to Implement AA Tree
Primitive Type Streams in Java 8
Practical Java Examples of the Big O Notation
Spring Boot Security Auto-Configuration
Java Program to Implement Euler Circuit Problem
Spring Boot - Actuator
Java Program to Implement Fermat Primality Test Algorithm
Wrapper Classes in Java
Different Ways to Capture Java Heap Dumps
Quick Intro to Spring Cloud Configuration
Java Program to Find Path Between Two Nodes in a Graph
Guava – Join and Split Collections
Java – Create a File
Spring Data MongoDB Transactions
Read an Outlook MSG file
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Validations for Enum Types
Spring Boot - Apache Kafka
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Spring Security Custom AuthenticationFailureHandler
Java Program to Implement VList
Java Program to Implement Lloyd’s Algorithm
Hướng dẫn Java Design Pattern – Chain of Responsibility
Testing an OAuth Secured API with Spring MVC
Java Program to Generate Random Numbers Using Probability Distribution Function