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:
Getting Started with Forms in Spring MVC
Spring Webflux and CORS
Converting a Stack Trace to a String in Java
Hướng dẫn Java Design Pattern – Command
Java Program to Perform Cryptography Using Transposition Technique
Registration with Spring Security – Password Encoding
Spring Boot Gradle Plugin
Guide to the Java Clock Class
Connect through a Proxy
HttpClient 4 Cookbook
Jackson Unmarshalling JSON with Unknown Properties
Java Program to Implement Jarvis Algorithm
Custom Error Pages with Spring MVC
Các kiểu dữ liệu trong java
Apache Commons Collections SetUtils
Compact Strings in Java 9
Xây dựng ứng dụng Client-Server với Socket trong Java
Sắp xếp trong Java 8
Guide To CompletableFuture
Java Program to Print only Odd Numbered Levels of a Tree
Returning Custom Status Codes from Spring Controllers
Java – Byte Array to Reader
Assertions in JUnit 4 and JUnit 5
Server-Sent Events in Spring
Convert String to int or Integer in Java
Difference Between Wait and Sleep in Java
Extract network card address
Java Program to Implement the One Time Pad Algorithm
Spring Boot Actuator
Java Program to Implement Queue using Linked List
Handle EML file with JavaMail
Luồng Daemon (Daemon Thread) trong Java