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 Check if a Given Graph Contain Hamiltonian Cycle or Not
Java Program to Implement vector
Java Program to implement Bit Matrix
Chương trình Java đầu tiên
Java Program to Permute All Letters of an Input String
Working with Network Interfaces in Java
A Guide to the Java LinkedList
Guide to Spring 5 WebFlux
Converting String to Stream of chars
Spring Security – Reset Your Password
Getting Started with Stream Processing with Spring Cloud Data Flow
Java List UnsupportedOperationException
Java Program to Print only Odd Numbered Levels of a Tree
Comparing Two HashMaps in Java
JPA/Hibernate Persistence Context
Spring Cloud – Bootstrapping
Hướng dẫn Java Design Pattern – Dependency Injection
Guide to @JsonFormat in Jackson
Using a Mutex Object in Java
Redirect to Different Pages after Login with Spring Security
Spring @RequestMapping New Shortcut Annotations
Java Program to Implement Hash Tables with Double Hashing
Java Program to add two large numbers using Linked List
Spring Boot - Building RESTful Web Services
Java Program to Generate Random Numbers Using Probability Distribution Function
Comparing Long Values in Java
Map Serialization and Deserialization with Jackson
Java Program to implement Sparse Vector
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Tiêu chuẩn coding trong Java (Coding Standards)
Spring Data MongoDB – Indexes, Annotations and Converters
Java Program to Implement Hash Tables Chaining with Binary Trees