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 Check if it is a Sparse Matrix
Lớp TreeMap trong Java
Java toString() Method
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Uploading MultipartFile with Spring RestTemplate
Lớp LinkedHashMap trong Java
XML-Based Injection in Spring
Cachable Static Assets with Spring MVC
Java Streams vs Vavr Streams
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
How to Add a Single Element to a Stream
The Registration API becomes RESTful
Spring WebClient and OAuth2 Support
Mệnh đề Switch-case trong java
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
A Guide to BitSet in Java
Java Program to Implement Johnson’s Algorithm
Hướng dẫn sử dụng Lớp FilePermission trong java
HashMap trong Java hoạt động như thế nào?
Java Program to Check for balanced parenthesis by using Stacks
Giới thiệu Design Patterns
Các nguyên lý thiết kế hướng đối tượng – SOLID
Java Program to Implement Hash Tables Chaining with List Heads
Java List UnsupportedOperationException
Hướng dẫn Java Design Pattern – Facade
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Java Program to Implement Disjoint Set Data Structure
Java Program to Implement Sieve Of Eratosthenes
Java Program to Implement SynchronosQueue API
String Joiner trong Java 8
Guide to the Synchronized Keyword in Java
Spring Boot Integration Testing with Embedded MongoDB