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:
Handle EML file with JavaMail
Bootstrapping Hibernate 5 with Spring
Java Program to Implement Interpolation Search Algorithm
Autoboxing và Unboxing trong Java
Receive email by java client
Java Program to Implement Gaussian Elimination Algorithm
Java Program to Implement Queue using Linked List
Giới thiệu Google Guice – Dependency injection (DI) framework
Remove the First Element from a List
Spring Boot Application as a Service
Spring Data JPA and Null Parameters
Java Program to Implement Nth Root Algorithm
Spring Boot - Twilio
How to Delay Code Execution in Java
How to Add a Single Element to a Stream
Spring Boot - Internationalization
Java Program to Implement Attribute API
Guide to System.gc()
Exploring the New Spring Cloud Gateway
Java Program to Implement LinkedBlockingQueue API
Java Program to Solve a Matching Problem for a Given Specific Case
REST Pagination in Spring
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Marker Interface trong Java
Java Program to Implement Euler Circuit Problem
JUnit5 @RunWith
Java Program to Find Strongly Connected Components in Graphs
Guide to UUID in Java
HashMap trong Java hoạt động như thế nào?
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java – Reader to InputStream
RestTemplate Post Request with JSON