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:
Xây dựng ứng dụng Client-Server với Socket trong Java
Comparing Dates in Java
Tính đa hình (Polymorphism) trong Java
Java Program to Find the Nearest Neighbor Using K-D Tree Search
Easy Ways to Write a Java InputStream to an OutputStream
Java Program to Perform Polygon Containment Test
A Quick JUnit vs TestNG Comparison
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Java Program to Find Nearest Neighbor for Dynamic Data Set
Join and Split Arrays and Collections in Java
Mix plain text and HTML content in a mail
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Java Program to Implement Segment Tree
Logout in an OAuth Secured Application
Spring Data – CrudRepository save() Method
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java Program to find the peak element of an array using Binary Search approach
Recommended Package Structure of a Spring Boot Project
Giới thiệu java.io.tmpdir
Spring MVC Setup with Kotlin
Từ khóa throw và throws trong Java
Java 8 Stream findFirst() vs. findAny()
A Guide to Concurrent Queues in Java
The XOR Operator in Java
Java Program to implement Circular Buffer
Java – InputStream to Reader
Java Program to Solve TSP Using Minimum Spanning Trees
Java Program to Implement the Program Used in grep/egrep/fgrep
More Jackson Annotations
CyclicBarrier in Java
Guide To CompletableFuture