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 Brent Cycle Algorithm
Java Program to Implement Leftist Heap
Primitive Type Streams in Java 8
Java Program to Implement Aho-Corasick Algorithm for String Matching
Java Program to Implement Ternary Search Algorithm
Introduction to the Java NIO Selector
Spring Security – Reset Your Password
Creating a Custom Starter with Spring Boot
Introduction to Thread Pools in Java
Spring Data Reactive Repositories with MongoDB
Java Program to Encode a Message Using Playfair Cipher
Java Program to Implement Suffix Array
Filtering a Stream of Optionals in Java
Performance Difference Between save() and saveAll() in Spring Data
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
HandlerAdapters in Spring MVC
Java Program to Implement Binary Tree
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
A Guide to BitSet in Java
Hướng dẫn Java Design Pattern – Strategy
Overview of the java.util.concurrent
Error Handling for REST with Spring
Generating Random Dates in Java
Guide to DelayQueue
Java Program to Implement SimpeBindings API
Java Program to Implement Johnson’s Algorithm
Java 8 StringJoiner
Send an email with an attachment
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Logging a Reactive Sequence
Base64 encoding và decoding trong Java 8
Custom Error Pages with Spring MVC