Java program to convert the inputstream into byte array
www.theitroad.com
In Java, you can convert an InputStream
object into a byte array using the ByteArrayOutputStream
class. Here's an example of how to do it:
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamToByteArrayExample { public static void main(String[] args) { InputStream inputStream = ... // Get the InputStream object from a source byte[] byteArray = null; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } byteArray = byteArrayOutputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } if (byteArray != null) { System.out.println("Byte Array length: " + byteArray.length); } } }
In the above example, we define a main
method that takes an InputStream
object as input and converts it into a byte array using ByteArrayOutputStream
. The input stream is read using a byte buffer of size 1024, and the bytes are written to the ByteArrayOutputStream
object until there is no more data in the stream. Finally, the byte array is obtained by calling the toByteArray
method on the ByteArrayOutputStream
object.
Note that you need to handle any IOException
that might occur during the conversion. Also, make sure to close the input stream after the conversion is complete to free up system resources.