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:
Chương trình Java đầu tiên
New Features in Java 10
The Registration API becomes RESTful
Convert Hex to ASCII in Java
Introduction to Spring Boot CLI
Spring NoSuchBeanDefinitionException
Spring Boot - Scheduling
Dynamic Proxies in Java
Wrapper Classes in Java
Java Program to subtract two large numbers using Linked Lists
Java Program to Implement ArrayBlockingQueue API
Converting String to Stream of chars
Java Program to Implement Fenwick Tree
Hướng dẫn sử dụng Java Reflection
Java Program to Implement Queue using Two Stacks
HandlerAdapters in Spring MVC
Java Program to Perform the Shaker Sort
Java Program to Create a Balanced Binary Tree of the Incoming Data
Spring 5 Testing with @EnabledIf Annotation
Base64 encoding và decoding trong Java 8
Quick Guide to the Java StringTokenizer
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Spring WebClient Requests with Parameters
Java Program to Implement K Way Merge Algorithm
Java Program to Implement Fibonacci Heap
Test a REST API with Java
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
The “final” Keyword in Java
Java Program to Represent Graph Using Incidence List
Marker Interface trong Java
Java – Get Random Item/Element From a List
Concurrent Test Execution in Spring 5