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:
Sử dụng CountDownLatch trong Java
Java Program to Implement HashSet API
Luồng Daemon (Daemon Thread) trong Java
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Send email with authentication
Performance Difference Between save() and saveAll() in Spring Data
Receive email using IMAP
Java Program to Implement the MD5 Algorithm
HttpClient with SSL
Java Program to Solve Knapsack Problem Using Dynamic Programming
Java Program to Implement Suffix Array
Test a REST API with Java
Guava Collections Cookbook
Lớp Properties trong java
A Guide to the Java ExecutorService
Java Program to Implement Shoelace Algorithm
Guide to ThreadLocalRandom in Java
Java Program to Implement Expression Tree
@Lookup Annotation in Spring
Weak References in Java
Spring Data Java 8 Support
Simple Single Sign-On with Spring Security OAuth2
Arrays.asList vs new ArrayList(Arrays.asList())
Dockerizing a Spring Boot Application
How to use the Spring FactoryBean?
Spring Boot - Application Properties
Java – Reader to InputStream
LinkedHashSet trong java
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
Hướng dẫn Java Design Pattern – Flyweight
Java Program to Implement Patricia Trie
Immutable Map Implementations in Java