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:
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Solve a Matching Problem for a Given Specific Case
DistinctBy in the Java Stream API
Java Program to Implement JobStateReasons API
Guide to java.util.concurrent.Locks
Logging a Reactive Sequence
Spring Boot Gradle Plugin
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Serialize Only Fields that meet a Custom Criteria with Jackson
An Intro to Spring Cloud Vault
Java Program to Implement DelayQueue API
An Intro to Spring Cloud Task
A Guide to LinkedHashMap in Java
Java Program to Generate a Random Subset by Coin Flipping
Java 8 Predicate Chain
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
REST Web service: Upload và Download file với Jersey 2.x
Jackson Unmarshalling JSON with Unknown Properties
Java Program to Implement the MD5 Algorithm
Java Program to Implement Threaded Binary Tree
Spring 5 Testing with @EnabledIf Annotation
4 tính chất của lập trình hướng đối tượng trong Java
Consuming RESTful Web Services
How to Read a File in Java
Generic Constructors in Java
Spring Boot Change Context Path
Java – String to Reader
Call Methods at Runtime Using Java Reflection
How to Kill a Java Thread
Từ khóa this và super trong Java
Check If Two Lists are Equal in Java