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 Program to Implement CopyOnWriteArraySet API
Java Program to Implement Singly Linked List
Immutable Map Implementations in Java
Why String is Immutable in Java?
Hướng dẫn Java Design Pattern – Adapter
Java Program to Implement CountMinSketch
Java Program to Implement Red Black Tree
Hướng dẫn sử dụng String Format trong Java
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
A Guide to Queries in Spring Data MongoDB
Java Program to Find Transitive Closure of a Graph
Java CyclicBarrier vs CountDownLatch
Setting the Java Version in Maven
Assert an Exception is Thrown in JUnit 4 and 5
LinkedHashSet trong Java hoạt động như thế nào?
Composition, Aggregation, and Association in Java
Guide to PriorityBlockingQueue in Java
Refactoring Design Pattern với tính năng mới trong Java 8
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java Program to Implement Euler Circuit Problem
Java Program to Generate Random Numbers Using Middle Square Method
Guide to Dynamic Tests in Junit 5
Prevent Cross-Site Scripting (XSS) in a Spring Application
Control the Session with Spring Security
Anonymous Classes in Java
Java Program to Compute Determinant of a Matrix
A Guide to JUnit 5 Extensions
Java Program to Perform Addition Operation Using Bitwise Operators
Java 14 Record Keyword
Java Program to Implement Queue using Linked List
Getting the Size of an Iterable in Java
Logout in an OAuth Secured Application