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:
Weak References in Java
Spring Security Logout
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Java Program to Implement LinkedList API
Serve Static Resources with Spring
How to Get All Dates Between Two Dates?
Fixing 401s with CORS Preflights and Spring Security
How to Get All Spring-Managed Beans?
A Guide to Java SynchronousQueue
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Spring Security Login Page with React
Spring Security – security none, filters none, access permitAll
Java Program to Implement Hash Tables with Quadratic Probing
Hướng dẫn Java Design Pattern – Command
Chuyển đổi từ HashMap sang ArrayList
Introduction to Thread Pools in Java
Retrieve User Information in Spring Security
Jackson – Bidirectional Relationships
Java Program to Compute Determinant of a Matrix
Serialize Only Fields that meet a Custom Criteria with Jackson
Adding Shutdown Hooks for JVM Applications
Java Program to Implement Caesar Cypher
Uploading MultipartFile with Spring RestTemplate
Spring Cloud – Tracing Services with Zipkin
Jackson Annotation Examples
Map Serialization and Deserialization with Jackson
Date Time trong Java 8
Java Program to Implement Sorted List
Java Program to Find Inverse of a Matrix
Java Program to Implement Kosaraju Algorithm
Java Program to implement Priority Queue
Changing Annotation Parameters At Runtime