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 Perform Right Rotation on a Binary Search Tree
Converting between an Array and a List in Java
Rate Limiting in Spring Cloud Netflix Zuul
Most commonly used String methods in Java
Spring Security OAuth2 – Simple Token Revocation
Java Program to Implement Heap Sort Using Library Functions
Spring RequestMapping
Java Program to Check if a Matrix is Invertible
Guide to the Volatile Keyword in Java
Java Program to Perform Complex Number Multiplication
Java Program to Implement the Monoalphabetic Cypher
Using the Not Operator in If Conditions in Java
Split a String in Java
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Spring Boot - Actuator
Apache Tiles Integration with Spring MVC
Introduction to Apache Commons Text
Recommended Package Structure of a Spring Boot Project
A Quick JUnit vs TestNG Comparison
Hướng dẫn Java Design Pattern – Adapter
A Guide to Concurrent Queues in Java
Hướng dẫn Java Design Pattern – Visitor
Ép kiểu trong Java (Type casting)
Giới thiệu Aspect Oriented Programming (AOP)
Apache Commons Collections Bag
Using Optional with Jackson
Spring REST API with Protocol Buffers
Lập trình đa luồng với CompletableFuture trong Java 8
Properties with Spring and Spring Boot
Reversing a Linked List in Java
Transaction Propagation and Isolation in Spring @Transactional
Spring Cloud AWS – RDS