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:
Phương thức forEach() trong java 8
Finding Max/Min of a List or Collection
Deploy a Spring Boot App to Azure
An Introduction to ThreadLocal in Java
How to Add a Single Element to a Stream
Hướng dẫn Java Design Pattern – Strategy
Introduction to Apache Commons Text
New Features in Java 10
Hướng dẫn Java Design Pattern – Memento
Jackson Date
Versioning a REST API
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
XML-Based Injection in Spring
Add Multiple Items to an Java ArrayList
Java – InputStream to Reader
Wiring in Spring: @Autowired, @Resource and @Inject
How to Define a Spring Boot Filter?
Spring Boot - Tracing Micro Service Logs
Quick Guide to @RestClientTest in Spring Boot
Java Program to Check Multiplicability of Two Matrices
Guide to Java 8’s Collectors
Spring REST API + OAuth2 + Angular
Spring Web Annotations
Spring Webflux with Kotlin
Xử lý ngoại lệ trong Java (Exception Handling)
Check if there is mail waiting
Base64 encoding và decoding trong Java 8
Java Program to Implement Rolling Hash
Guide to the ConcurrentSkipListMap
Hướng dẫn Java Design Pattern – Bridge
Spring Boot - Internationalization