1. Introduction
In this short tutorial, we will present how to convert an InputStream to ByteBuffer using Java built-in methods and libraries like: Guava
and Apache Commons IO
. Buffer is a container for data of a specific primitive type introduced in Java 8. In this case, byte
will be our primitive type.
For more Java I/O related articles, check the following links:
2. Convert InputStream to ByteBuffer using plain Java
In this example, we will use ByteArrayInputStream
to read bytes and put them into byteBuffer until the end of the stream initialStream.available() == 0
. Before the main loop the method initialStream.available())
will return the exact size of the underlying data:
3. Convert InputStream to ByteBuffer using Guava
Converting InputStream to ByteByffer could be achieved with external libraries like Guava
:
In this example we use ByteStreams.toByteArray
method from Guava
that converts an InputStream
into a byte array. Then, we create ByteBuffer
object that wraps that byte array.
The latest version of Guava
library is available under the following links:
4. InputStream to ByteBuffer using Apache Commons IO
library
Apache Commons IO
library comes with method IOUtils.readFully
that allows us to rewrite ReadableByteChannel
into ByteBuffer
:
The ReadableByteChannel
was created using newChannel
method from java.nio.channels.Channels
package.
The latest version of the library could be found here: Maven Apache Commons IO 2.6
5. Conclusion
In this tutorial, we illustrated how to convert InputStream into the ByteBuffer object that is a wrapper object for a byte array in Java.
As always, code use in this article is available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}