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:
Spring MVC Async vs Spring WebFlux
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Spring REST API + OAuth2 + Angular
Migrating from JUnit 4 to JUnit 5
Quick Intro to Spring Cloud Configuration
Shuffling Collections In Java
Spring @RequestMapping New Shortcut Annotations
Java Program to Implement Sorted Circularly Singly Linked List
Versioning a REST API
Spring Boot Change Context Path
Java Program to Implement Sparse Array
Properties with Spring and Spring Boot
Java Program to Implement Sieve Of Atkin
Spring JDBC
Giới thiệu SOAP UI và thực hiện test Web Service
Lớp HashMap trong Java
REST Web service: Basic Authentication trong Jersey 2.x
Java Program to Perform Sorting Using B-Tree
Remove All Occurrences of a Specific Value from a List
Adding a Newline Character to a String in Java
ArrayList trong java
Send email with JavaMail
Java Program to Implement Max Heap
Test a REST API with Java
Java 9 Stream API Improvements
Java – Byte Array to Reader
Spring MVC and the @ModelAttribute Annotation
Java – Reader to Byte Array
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Implement Gale Shapley Algorithm
Java Program to Perform Quick Sort on Large Number of Elements
Java Program to Implement Quick Sort with Given Complexity Constraint