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:
A Guide to JPA with Spring
Java Program to Implement Sparse Matrix
Overflow and Underflow in Java
Jackson – Decide What Fields Get Serialized/Deserialized
Introduction to Project Reactor Bus
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Java Program to Implement Interpolation Search Algorithm
DynamoDB in a Spring Boot Application Using Spring Data
Java Program to Implement LinkedBlockingQueue API
Quick Intro to Spring Cloud Configuration
Guide to Java Instrumentation
Comparing Arrays in Java
Refactoring Design Pattern với tính năng mới trong Java 8
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Spring Boot - Flyway Database
Lớp Properties trong java
Java Program to Find a Good Feedback Edge Set in a Graph
Các kiểu dữ liệu trong java
Spring Boot - File Handling
Zipping Collections in Java
Tính kế thừa (Inheritance) trong java
Java Program to Implement Hash Trie
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Collection trong java
What is Thread-Safety and How to Achieve it?
Java Program to Find the Connected Components of an UnDirected Graph
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Apache Commons Collections Bag
JUnit 5 @Test Annotation
Spring Boot Tutorial – Bootstrap a Simple Application
Spring Autowiring of Generic Types
Java Program to Implement Weight Balanced Tree