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:
Spring Boot - Quick Start
Java Program to Implement Bellman-Ford Algorithm
Java Program to Implement Gabow Algorithm
Spring Security and OpenID Connect
Java Program to Find the Longest Path in a DAG
An Example of Load Balancing with Zuul and Eureka
Getting Started with Custom Deserialization in Jackson
Mockito and JUnit 5 – Using ExtendWith
Java Program to Implement Sieve Of Atkin
Introduction to Spring Cloud OpenFeign
Java Program to Implement Adjacency List
Validations for Enum Types
Java InputStream to Byte Array and ByteBuffer
HashSet trong java
Hướng dẫn Java Design Pattern – Chain of Responsibility
Hướng dẫn Java Design Pattern – State
Biểu thức Lambda trong Java 8 – Lambda Expressions
Fixing 401s with CORS Preflights and Spring Security
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Hướng dẫn Java Design Pattern – Prototype
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Represent Graph Using Incidence Matrix
Send email with SMTPS (eg. Google GMail)
Spring Boot - Code Structure
Java Program to Implement Flood Fill Algorithm
Java Program to Implement LinkedBlockingDeque API
A Guide to HashSet in Java
Lớp Arrarys trong Java (Arrays Utility Class)
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Java Program to Implement the Monoalphabetic Cypher
Why String is Immutable in Java?