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:
Java – Get Random Item/Element From a List
Java Program to Describe the Representation of Graph using Incidence List
Introduction to Spring MVC HandlerInterceptor
Period and Duration in Java
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Java Program to Emulate N Dice Roller
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Class Loaders in Java
Implementing a Binary Tree in Java
Integer Constant Pool trong Java
Anonymous Classes in Java
How to Get a Name of a Method Being Executed?
Apache Commons Collections Bag
Java Program to Implement Strassen Algorithm
Java Program to Represent Graph Using 2D Arrays
Logging in Spring Boot
Java Program to Solve Tower of Hanoi Problem using Stacks
Collect a Java Stream to an Immutable Collection
Receive email by java client
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Create a Custom Auto-Configuration with Spring Boot
Spring Boot - Enabling Swagger2
Autoboxing và Unboxing trong Java
Java Program to Implement Sorted Array
Java InputStream to String
Removing all duplicates from a List in Java
Java Program to Implement ConcurrentLinkedQueue API
Beans and Dependency Injection
Sử dụng CyclicBarrier trong Java
Spring Boot - Quick Start
Java Program to Implement Skew Heap
Java Program to implement Bit Set