In this short tutorial, we will present how to convert an InputStream to ByteBuffer using Java built-in methods and libraries like:
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
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
Converting InputStream to ByteByffer could be achieved with external libraries like
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 was created using
newChannel method from
The latest version of the library could be found here: Maven Apache Commons IO 2.6
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.