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 Hash Tables
The Registration API becomes RESTful
Guide to java.util.concurrent.Locks
Spring Webflux with Kotlin
Giới thiệu Google Guice – Injection, Scope
Request Method Not Supported (405) in Spring
Spring NoSuchBeanDefinitionException
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Find Nearest Neighbor Using Linear Search
Java Program to Implement Hash Tree
New Features in Java 15
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Merging Streams in Java
Java Program to Implement Pagoda
A Guide to Apache Commons Collections CollectionUtils
Abstract class và Interface trong Java
Spring WebFlux Filters
Spring Boot Gradle Plugin
Introduction to Java Serialization
Java 9 Stream API Improvements
Java Program to implement Bit Matrix
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Convert XML to JSON Using Jackson
Jackson – Bidirectional Relationships
Java Program to Implement Rope
Spring 5 Testing with @EnabledIf Annotation
Java Program to Find Nearest Neighbor for Dynamic Data Set
Using a Spring Cloud App Starter
Enum trong java
Java – Create a File
Guide to java.util.Formatter
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph