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:
Introduction to Spring Data JDBC
ClassNotFoundException vs NoClassDefFoundError
Java Program to Compute the Area of a Triangle Using Determinants
Template Engines for Spring
Spring NoSuchBeanDefinitionException
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Inheritance and Composition (Is-a vs Has-a relationship) in Java
An Example of Load Balancing with Zuul and Eureka
Từ khóa this và super trong Java
Spring Security Logout
HttpClient 4 – Send Custom Cookie
The Registration Process With Spring Security
HttpClient 4 – Follow Redirects for POST
Java Program to Implement Stack
Spring Boot - Building RESTful Web Services
Java – Create a File
Java Program to Implement TreeMap API
Most commonly used String methods in Java
Spring Security Remember Me
Java Program to Perform Finite State Automaton based Search
Java – Reader to Byte Array
Guide to the Volatile Keyword in Java
Java Program to Perform Deletion in a BST
Java Program to Solve any Linear Equation in One Variable
Java Program to Implement Disjoint Sets
Java Program to Implement Rope
Java Program to Implement Hash Tree
Removing all Nulls from a List in Java
Introduction to the Functional Web Framework in Spring 5
Java Program to Implement LinkedBlockingQueue API
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Interface trong Java 8 – Default method và Static method