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:
Guide to the ConcurrentSkipListMap
Encode a String to UTF-8 in Java
Consuming RESTful Web Services
Error Handling for REST with Spring
Spring Boot Configuration with Jasypt
HashMap trong Java hoạt động như thế nào?
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Sử dụng CountDownLatch trong Java
Receive email by java client
Giới thiệu Aspect Oriented Programming (AOP)
Java Program to Create the Prufer Code for a Tree
Converting Iterator to List
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Implement Sorted Vector
Introduction to Java 8 Streams
Biến trong java
Posting with HttpClient
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Inject Parameters into JUnit Jupiter Unit Tests
Lập trình hướng đối tượng (OOPs) trong java
String Operations with Java Streams
Một số từ khóa trong Java
Java Program to Implement Warshall Algorithm
Guide to Spring Cloud Kubernetes
HTTP Authentification and CGI/Servlet
Cài đặt và sử dụng Swagger UI
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Check Cycle in a Graph using Graph traversal
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Java Program to Implement Gauss Jordan Elimination
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Hướng dẫn sử dụng String Format trong Java