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:
Sort a HashMap in Java
Java Program to Perform Search in a BST
Java Program to Implement Pollard Rho Algorithm
Spring Cloud AWS – EC2
How to Count Duplicate Elements in Arraylist
Quick Guide to the Java StringTokenizer
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java Program to Implement Range Tree
Feign – Tạo ứng dụng Java RESTful Client
How to Read a File in Java
Properties with Spring and Spring Boot
Guide to System.gc()
Cài đặt và sử dụng Swagger UI
A Guide to EnumMap
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Spring Boot with Multiple SQL Import Files
Java Program to Create a Random Graph Using Random Edge Generation
Java Program to Implement the Hill Cypher
Function trong Java 8
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Xây dựng ứng dụng Client-Server với Socket trong Java
Functional Interfaces in Java 8
Remove the First Element from a List
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Send email with JavaMail
Convert Character Array to String in Java
Java Program to Implement Treap
Phân biệt JVM, JRE, JDK
Spring RequestMapping
Spring Boot - Securing Web Applications
Java Program to Perform Sorting Using B-Tree