Java convert stream to byte

How to Convert InputStream to Byte Array in Java — 2 Examples

Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as a byte array, In order to pass output to a method that accepts byte array rather than InputStream . One popular example of this, I have seen is an older version of Apache commons-codec, whi le converting byte array to the hex string. Though, a later version of the same library does provide a n overloaded method, to accept InputStream . Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometimes you need String or byte array, instead of InputStream .

Earlier we have see n 5 ways to convert InputStream to String in Java, we can use some of the techniques from there while getting the yte array from InputStream in Java. If you like to use Apache commons library, which I think you should, there is a utility class called IOUtils , which can be used to easily convert InputStream to byte array in Java.

Читайте также:  Css как обнулить класс

If you don’t like using open source libraries for such kinds of things, and like to write your own method, you can easily do so by using standard Java File API. In this Java tutorial we will see examples of both ways to convert InputStream to byte array in Java.

Java program to convert InputStream to byte array in Java

Here is complete code example of reading InputStream as byte array in Java. This Java program has two methods, one uses Apache commons IOUtils library to convert InputStream as byte array, while other uses core Java class methods. If you look at Apache commons code, it’s ju st a one liner and it’s tested for various kind of input e.g. text file, binary file, images, and both large and small files.

By writing your own method for common utilities, which is good in sense of ownership; It’s difficult to get same kind of testing exposure. That’s the reason I prefer to use open source libraries, like Apache commons and Google Guava, along with JDK. They effectively complement standard Java library, and with Maven, it’s pretty easy to manage dependency. By the way, In this example, w e are reading a small text file using FileInputStream in Java.

import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; /** * Java program to convert InputStream to byte array in Java. * This Java examples uses Apache commons IOUtils to * create byte array from InputStream * and Simply Java method to convert InputStream to byte array. * * @author Javin Paul */ public class InputStreamToByteArray < public static void main(String args[]) throws FileNotFoundException, IOException < //Converting InputStream to byte array using apche commons IO library int length = toByteArrayUsingCommons( new FileInputStream("C:/temp/abc.txt")).length; System.out.println("Length of byte array created from InputStream in Java using IOUtils : " + length); //Converting InputStream to Byte arrray using Java code length = toByteArrayUsingJava( new FileInputStream("C:/temp/abc.txt")).length; System.out.println("Length of Byte array created from FileInputStream in Java : " + length); > /* * Converts InputStream to ByteArray in Java using Apache commons IOUtils class */ public static byte[] toByteArrayUsingCommons(InputStream is) throws IOException< return IOUtils.toByteArray(is); > /* * Read bytes from inputStream and writes to OutputStream, * later converts OutputStream to byte array in Java. */ public static byte[] toByteArrayUsingJava(InputStream is) throws IOException< ByteArrayOutputStream baos = new ByteArrayOutputStream(); int reads = is.read(); while(reads != -1)< baos.write(reads); reads = is.read(); > return baos.toByteArray(); > > Output: Length of byte array created from InputStream in Java using IOUtils : 27 Length of Byte array created from FileInputStream in Java : 27 

That’s all on How to convert InputStream to byte array in Java . You can this trick to get byte array from any kind of InputStream e.g. ObjectInputStream , FileInputStream or DataInputStream in Java.

Читайте также:  No python found running

Источник

How to convert InputStream to Byte Array in Java

In this tutorial, we are going to learn how to convert an InputStream to a byte array using plain Java and external libraries like Guava or Apache Commons IO. In many cases, there is a need to use byte [] instead of Strings mainly because processing arrays is fast and not resource consuming.

For more Java I/O related articles, check the following links:

2. Convert InputStream to byte array using ByteArrayOutputStream

Natural way to convert an InputStream to byte array is to use plan Java solution based on ByteArrayOutputStream :

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamToByteArrayUsingByteArrayOutputStream < public static void main(String[] args) throws IOException < InputStream initialStream = new ByteArrayInputStream(new byte[] < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >); // example input stream ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; while ((nRead = initialStream.read(data, 0, data.length)) != -1) < buffer.write(data, 0, nRead); >buffer.flush(); byte[] byteArray = buffer.toByteArray(); > > 

In this example, we created ByteArrayOutputStream and write to it blocks of read data from the InputStream . Then, we used the toByteArray() method to get wanted byte array.

BTW. we use example list of bytes that represent our domain name:

System.out.println(new String(new byte[])); // frontbackend 

3. InputStream to byte [] using ByteArrayInputStream

When we have the opportunity to use ByteArrayInputStream , instead of any other different InputStream , this will be the best way to get byte array out stream. This is because ByteArrayInputStream contains method read that takes byte[

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamToByteArrayUsingByteArrayInputStream < public static void main(String[] args) throws IOException < InputStream initialStream = new ByteArrayInputStream(new byte[] < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >); // example input stream byte[] targetArray = new byte[initialStream.available()]; initialStream.read(targetArray); > > 

4. Conversion from InputStream to a byte array using Guava

To convert InputStream to byte [] we can also use external libraries like Guava . The Guava based solution using ByteStreams utility class looks like the following:

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import com.google.common.io.ByteStreams; public class InputStreamToByteArrayUsingGuava < public static void main(String[] args) throws IOException < InputStream initialStream = new ByteArrayInputStream(new byte[] < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >); byte[] targetArray = ByteStreams.toByteArray(initialStream); > > 

To start working with Guava we should include special dependency to our project:

 com.google.guava guava 28.2-jre  

The latest version of Guava library is available here:

5. Convert Using Apache Commons IO

Apache Commons IO comes with similar to Guava solution to convert an InputStream to a byte array:

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; public class InputStreamToByteArrayUsingIOUtils < public static void main(String[] args) throws IOException < InputStream initialStream = new ByteArrayInputStream(new byte[] < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >); byte[] byteArray = IOUtils.toByteArray(initialStream); > > 

Of course, first we need to include Apache Commons IO dependency to our project or download JAR . The following presents the way we could include library in POM.xml file:

The latest version of the library could be found here: Maven Apache Commons IO 2.6

6. Conclusion

This article presented several ways to convert an InputStream to byte array in Java using built-in methods from Java IO and using libraries like: Guava or Apache Commons IO .

The examples illustrated in this tutorial can be found in our GitHub project.

Источник

How to Convert InputStream to byte[]

This article illustrates different ways to Convert InputStream to a byte[] (or Byte Array) using Apache Common IO, Guava, and Plain Java.

Overview

The InputStream is a byte stream, which we read from almost anything in Java. Many ways are available to convert an InputStream to a byte[] or a ByteBuffer. In this tutorial, we will cover them one by one.

Before we do that, let’s quickly have a look at how to create an InputStream instance from a byte[] (Byte Array)

Converting a Byte Array to an InputStream

Let’s see a simple example of converting a byte[] to an InputStream in plain Java. We create a byte[] instance from a String object and use it to create an instance of the ByteArrayInputStream, a subclass of InputStream.

byte[] bytes = string.getBytes(UTF_8); InputStream inputStream = new ByteArrayInputStream(bytes);Code language: Java (java)

In the next part, we will see various ways of Converting an InputStream to a byte[].

InputStream to Byte Array Using Apache Commons IO

The Apache Commons IO Library provides many useful abstractions for basic File IO operations in Java. Next is a very simple and short way of creating byte[] from an InputStream.

Example of using Apache Commons IO to convert an InputStream to byte[]

byte[] bytes = IOUtils .toByteArray(inputStream);Code language: Java (java)

InputStream to Byte Array Using Guava Library

Similarly, the Guava Library also provides a simple and concise way. We can use the ByteStreams utility class, as shown in the following example. The toByteArray() method returns a byte[] containing all the bytes from the given InputStream.
Example of using Guava to convert an InputStream to byte[]

byte[] bytes = ByteStreams .toByteArray(inputStream);Code language: Java (java)

InputStream to Byte Array Using Plain Java

The Java InputStream provides the read(byte[]) method, which copies all available bytes into the provided array of bytes. However, to use this method, we need to provide an array of the exact size.

And to do that, we read the number of available bytes from the InputStream instance and initialize a byte[] of the same size.

Example of using plain Java to convert an InputStream to a byte[].

int size = inputStream.available(); byte[] bytes = new byte[size]; inputStream.read(bytes);Code language: Java (java)

This solution works for an InputStream of a fixed size. However, if the InputStream is a BufferedInputStream, the available() method returns the current buffer size and not the size of all bytes.

For such a BufferedInputStream instance, we can use the readAllBytes() method that returns the size of all bytes.

byte[] bytes = inputStream.readAllBytes();Code language: Java (java)

InputStream to ByteArray Manually

We saw several ways of converting an InputStream to a Byte Array, and they used different abstractions to simplify the process. However, if we want more control over the size of the buffer and the amount of memory being used, we can do the conversion manually.

We can iteratively read a fixed number of bytes from the InputStream instance and consume them before reading the next set of bytes.

Example of converting an InputSteram to byte[] manually.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bucket = new byte[1024]; int nReadBytes; while((nReadBytes = inputStream .read(bucket, 0, bucket.length)) !=-1)< byteArrayOutputStream.write(bucket, 0, nReadBytes); > byte[] bytes = byteArrayOutputStream.toByteArray();Code language: Java (java)

Firstly, we create an instance of the ByteArrayOutputStream, which is the consumer of our byte[]. Next, we make a byte[] bucket of a fixed size. During each iteration, we fill the bucket (of fixed size) from the InputStream and write it onto the ByteArrayOutputStream. And continue to do so until no more byes are left in the InputStream.

Summary

In this short tutorial, we covered different ways of Converting an InputStream to an array of bytes. We covered examples of using Apache Commons IO Library, Guava Library, and a couple of examples using Core Java. For more on Java, please visit Java Tutorials.

Please refer to our GitHub Repository for the complete source code of the examples.

Источник

Оцените статью