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:
Java Program to Implement Heap
Guide to the Fork/Join Framework in Java
Java Program to Implement Weight Balanced Tree
Mockito and JUnit 5 – Using ExtendWith
A Guide to BitSet in Java
So sánh HashMap và Hashtable trong Java
Converting String to Stream of chars
Shuffling Collections In Java
Introduction to Spring Data MongoDB
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Perform Searching Based on Locality of Reference
Lập trình hướng đối tượng (OOPs) trong java
Java Program to Implement Stack
Java – Reader to InputStream
Java Program to Implement Sorted List
Ways to Iterate Over a List in Java
Java Program to Implement Brent Cycle Algorithm
Converting Between a List and a Set in Java
Java – Combine Multiple Collections
Java Program to Find the Connected Components of an UnDirected Graph
Java Program to Implement PriorityBlockingQueue API
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Java Program to Perform Cryptography Using Transposition Technique
Guide to PriorityBlockingQueue in Java
Spring Data JPA @Modifying Annotation
Weak References in Java
StringBuilder vs StringBuffer in Java
How to Set TLS Version in Apache HttpClient
Java Program to Implement ArrayDeque API
Spring Boot Configuration with Jasypt
Java – Create a File
Java Map With Case-Insensitive Keys