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:
Ép kiểu trong Java (Type casting)
Registration – Activate a New Account by Email
Java Program to Implement LinkedTransferQueue API
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Simple Single Sign-On with Spring Security OAuth2
Introduction to Using Thymeleaf in Spring
LinkedHashSet trong Java hoạt động như thế nào?
Guide to WeakHashMap in Java
Serve Static Resources with Spring
Different Ways to Capture Java Heap Dumps
A Guide to Iterator in Java
Java Program to Solve TSP Using Minimum Spanning Trees
Giới thiệu Google Guice – Binding
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Java Program to Show the Duality Transformation of Line and Point
Java Program to Perform LU Decomposition of any Matrix
A Guide to the ViewResolver in Spring MVC
Spring 5 and Servlet 4 – The PushBuilder
Guide to the ConcurrentSkipListMap
Reactive WebSockets with Spring 5
Jackson Unmarshalling JSON with Unknown Properties
Java Program to Perform Searching Using Self-Organizing Lists
Java Convenience Factory Methods for Collections
Spring Data – CrudRepository save() Method
The Modulo Operator in Java
Hướng dẫn Java Design Pattern – Null Object
Java Program to Check if a Matrix is Invertible
How to Read HTTP Headers in Spring REST Controllers
Java Program to Implement K Way Merge Algorithm
DistinctBy in the Java Stream API
Batch Processing with Spring Cloud Data Flow
New Features in Java 13