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:
Jackson JSON Views
Consumer trong Java 8
Java Program to Implement Queue
Java Program to Implement LinkedHashSet API
Check If a File or Directory Exists in Java
Java Program to Implement Hamiltonian Cycle Algorithm
The Order of Tests in JUnit
Guide to the ConcurrentSkipListMap
How to Read HTTP Headers in Spring REST Controllers
Spring Web Annotations
Java Map With Case-Insensitive Keys
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Immutable Objects in Java
Java Program to Implement Warshall Algorithm
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Assertions in JUnit 4 and JUnit 5
Hướng dẫn Java Design Pattern – Adapter
Java – Create a File
Spring Security 5 for Reactive Applications
A Custom Data Binder in Spring MVC
Validate email address exists or not by Java Code
Java Program to Implement Gale Shapley Algorithm
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Using Spring ResponseEntity to Manipulate the HTTP Response
Assert an Exception is Thrown in JUnit 4 and 5
Java Program to Generate Random Numbers Using Multiply with Carry Method
Converting String to Stream of chars
Introduction to Thread Pools in Java
Từ khóa static và final trong java
Set Interface trong Java
Java Program to Implement Quick Sort Using Randomization
Apache Camel with Spring Boot