How to Convert InputStream to Byte Array in Java?
Last Updated :
30 Jan, 2023
In Java, input stream refers to an ordered flow of data in the form of bytes. This flow of data can be coming from various resources such as files, network programs, input devices, etc. In order to read such data, we have a Java InputStream Class in the Java IO API. There are several methods to convert this input stream into a byte array (or byte[]) which can be used as and when required. We'll now have a look at some methods to do the same which are listed as follows:
Methods:
- Using read(byte[]) or readAllBytes()
- Using ByteArrayOutputStream Class
- Using ByteStreams utility class
- Using Apache Commons IO Library
Now we will be discussing each and every method to detail in order and understanding the implementation the same via clean java programs as follows:
Method 1: Using read(byte[]) or readAllBytes()
In the InputStream class, we have a read() method where a byte array can be passed as a parameter to get the input stream data in the form of a byte array. But this method has a shortcoming that it can read the data at most the size of the array passed as a parameter. It works well only if we know the size of incoming data beforehand. The method returns an int value equal to the number of bytes read into the array or -1 if the stream end is reached.
Syntax:
Declaration read(byte[])
public int read​(byte[] byteArray)
throws IOException
To overcome the drawback of having to know the input size beforehand, we have another method called readAllBytes() since Java 9. This method can read all bytes available in the input stream. The method is way more faster and efficient in converting input stream to a byte array.
Syntax: readAllBytes()
public byte[] readAllBytes()
throws IOException
Example
Java
// Java Program to Convert InputStream to Byte Array
// Using read(byte[]) or readAllBytes()
// Importing required classes
import java.io.*;
import java.nio.charset.StandardCharsets;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a Input Stream here
// Usually it comes from files, programs
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks".getBytes(
StandardCharsets.UTF_8));
// Taking the InputStream data into a byte array
byte[] byteArray = null;
// Try block to check for exceptions
try {
byteArray = inputStream.readAllBytes();
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print and display the exceptions
System.out.println(e);
}
// Iterating over using for each loop
for (byte b : byteArray)
// Printing the content of byte array
System.out.print((char)b + " ");
}
}
OutputG e e k s F o r G e e k s
Example 2: Using ByteArrayOutputStream Class
This is an indirect method of conversion of input stream data into a byte array. Here we will be using an object of ByteArrayOutputStream class as a buffer. For this, we read each byte from a InputStream class and write it to a ByteArrayOutputStreamclass. Later we call toByteArray() that returns the output stream in the form of a byte array.
Example
Java
// Java Program to Convert InputStream to Byte Array
// Using ByteArrayOutputStream Class
// Importing required classes
import java.io.*;
import java.nio.charset.StandardCharsets;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a Input Stream here (usually it comes
// from files, programs, etc.)
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks".getBytes(
StandardCharsets.UTF_8));
// Taking the InputStream data into a byte array
// output stream
// Buffer size taken to be 1000 say.
byte[] buffer = new byte[1000];
// Creating an object of ByteArrayOutputStream class
ByteArrayOutputStream byteArrayOutputStream
= new ByteArrayOutputStream();
// Try block to check for exceptions
try {
int temp;
while ((temp = inputStream.read(buffer))
!= -1) {
byteArrayOutputStream.write(buffer, 0,
temp);
}
}
// Catch block to handle the exceptions
catch (IOException e) {
// Display the exception/s on the console
System.out.println(e);
}
// Mow converting byte array output stream to byte
// array
byte[] byteArray
= byteArrayOutputStream.toByteArray();
// Iterating over using for each loop
for (byte b : byteArray)
// Printing the content of byte array
System.out.print((char)b + " ");
}
}
OutputG e e k s F o r G e e k s
Method 3: Using ByteStreams utility class
ByteStreams utility class from the Guava Library has a direct method to convert input stream to a byte array.
Google Guava is an open-source(a decentralized software-development model that encourages open collaboration) set of common libraries for Java, mainly developed by Google engineers. It helps in reducing coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
Example
Java
// Java Program to Convert InputStream to Byte Array
// Using ByteArrayOutputStream Class
// Importing required classes, here additionally
// We are importing from Guava Library
import com.google.common.io.ByteStreams;
import java.io.*;
import java.nio.charset.StandardCharsets;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a Input Stream here
// usually it comes from files, programs
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks".getBytes(
StandardCharsets.UTF_8));
// Taking the InputStream data into a byte array
// using ByteStreams
byte[] byteArray = null;
// Try block to check for exceptions
try {
byteArray
= ByteStreams.toByteArray(inputStream);
}
// Catch block to handle the exceptions
catch (IOException e) {
// Display the exceptions on the console window
System.out.println(e);
}
// Iterating over using for each loop
for (byte b : byteArray)
// Printing the content of byte array
System.out.print((char)b + " ");
}
}
Method 4: Using Apache Commons IO Library
This method is very similar to using ByteStreams class. Here we make use of IOUtils class which has a similar method with the same name toByteArray() that returns the inputstream data as a byte array. The usage same we just need to use import org.apache.commons.io.IOUtils rather that ByteStreams of Guava Library.
Syntax:
byte[] byteArray = IOUtils.toByteArray(inputStream);
Note: However, this method often needs the addition of dependency to the editor.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read