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
import java.io.*;
import java.nio.charset.StandardCharsets;
class GFG {
public static void main(String[] args)
{
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks" .getBytes(
StandardCharsets.UTF_8));
byte [] byteArray = null ;
try {
byteArray = inputStream.readAllBytes();
}
catch (IOException e) {
System.out.println(e);
}
for ( byte b : byteArray)
System.out.print(( char )b + " " );
}
}
|
Output
G 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
import java.io.*;
import java.nio.charset.StandardCharsets;
class GFG {
public static void main(String[] args)
{
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks" .getBytes(
StandardCharsets.UTF_8));
byte [] buffer = new byte [ 1000 ];
ByteArrayOutputStream byteArrayOutputStream
= new ByteArrayOutputStream();
try {
int temp;
while ((temp = inputStream.read(buffer))
!= - 1 ) {
byteArrayOutputStream.write(buffer, 0 ,
temp);
}
}
catch (IOException e) {
System.out.println(e);
}
byte [] byteArray
= byteArrayOutputStream.toByteArray();
for ( byte b : byteArray)
System.out.print(( char )b + " " );
}
}
|
Output
G 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
import com.google.common.io.ByteStreams;
import java.io.*;
import java.nio.charset.StandardCharsets;
class GFG {
public static void main(String[] args)
{
InputStream inputStream = new ByteArrayInputStream(
"GeeksForGeeks" .getBytes(
StandardCharsets.UTF_8));
byte [] byteArray = null ;
try {
byteArray
= ByteStreams.toByteArray(inputStream);
}
catch (IOException e) {
System.out.println(e);
}
for ( byte b : byteArray)
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.
Share your thoughts in the comments
Please Login to comment...