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:
Removing all Nulls from a List in Java
Spring Boot - Eureka Server
Java Program to Perform Arithmetic Operations on Numbers of Size
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Interface trong Java 8 – Default method và Static method
Spring MVC Tutorial
Java Program to Perform Right Rotation on a Binary Search Tree
Lập trình đa luồng với CompletableFuture trong Java 8
HashSet trong java
Sử dụng CyclicBarrier trong Java
Introduction to Using FreeMarker in Spring MVC
Spring 5 WebClient
Documenting a Spring REST API Using OpenAPI 3.0
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Java Program to Find the Nearest Neighbor Using K-D Tree Search
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Spring REST API + OAuth2 + Angular
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Introduction to Java 8 Streams
Spring Boot - Google Cloud Platform
Java Program to Implement RenderingHints API
Java Program to Represent Graph Using Linked List
Java Program to Check Cycle in a Graph using Graph traversal
Converting Between Byte Arrays and Hexadecimal Strings in Java
Java List UnsupportedOperationException
Java Program to Implement Hopcroft Algorithm
Java Program to Implement Ternary Heap
Request a Delivery / Read Receipt in Javamail
Java – Random Long, Float, Integer and Double
Serialize Only Fields that meet a Custom Criteria with Jackson
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Compare Binary and Sequential Search